two_factors_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package db
  5. import (
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. "gogs.io/gogs/internal/errutil"
  10. )
  11. func Test_twoFactors(t *testing.T) {
  12. if testing.Short() {
  13. t.Skip()
  14. }
  15. t.Parallel()
  16. tables := []interface{}{new(TwoFactor), new(TwoFactorRecoveryCode)}
  17. db := &twoFactors{
  18. DB: initTestDB(t, "twoFactors", tables...),
  19. }
  20. for _, tc := range []struct {
  21. name string
  22. test func(*testing.T, *twoFactors)
  23. }{
  24. {"Create", test_twoFactors_Create},
  25. {"GetByUserID", test_twoFactors_GetByUserID},
  26. {"IsUserEnabled", test_twoFactors_IsUserEnabled},
  27. } {
  28. t.Run(tc.name, func(t *testing.T) {
  29. t.Cleanup(func() {
  30. err := clearTables(t, db.DB, tables...)
  31. if err != nil {
  32. t.Fatal(err)
  33. }
  34. })
  35. tc.test(t, db)
  36. })
  37. }
  38. }
  39. func test_twoFactors_Create(t *testing.T, db *twoFactors) {
  40. // Create a 2FA token
  41. err := db.Create(1, "secure-key", "secure-secret")
  42. if err != nil {
  43. t.Fatal(err)
  44. }
  45. // Get it back and check the Created field
  46. tf, err := db.GetByUserID(1)
  47. if err != nil {
  48. t.Fatal(err)
  49. }
  50. assert.Equal(t, db.NowFunc().Format(time.RFC3339), tf.Created.UTC().Format(time.RFC3339))
  51. // Verify there are 10 recover codes generated
  52. var count int64
  53. err = db.Model(new(TwoFactorRecoveryCode)).Count(&count).Error
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. assert.Equal(t, int64(10), count)
  58. }
  59. func test_twoFactors_GetByUserID(t *testing.T, db *twoFactors) {
  60. // Create a 2FA token for user 1
  61. err := db.Create(1, "secure-key", "secure-secret")
  62. if err != nil {
  63. t.Fatal(err)
  64. }
  65. // We should be able to get it back
  66. _, err = db.GetByUserID(1)
  67. if err != nil {
  68. t.Fatal(err)
  69. }
  70. // Try to get a non-existent 2FA token
  71. _, err = db.GetByUserID(2)
  72. expErr := ErrTwoFactorNotFound{args: errutil.Args{"userID": int64(2)}}
  73. assert.Equal(t, expErr, err)
  74. }
  75. func test_twoFactors_IsUserEnabled(t *testing.T, db *twoFactors) {
  76. // Create a 2FA token for user 1
  77. err := db.Create(1, "secure-key", "secure-secret")
  78. if err != nil {
  79. t.Fatal(err)
  80. }
  81. assert.True(t, db.IsUserEnabled(1))
  82. assert.False(t, db.IsUserEnabled(2))
  83. }