two_factors_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. if t.Failed() {
  38. break
  39. }
  40. }
  41. }
  42. func test_twoFactors_Create(t *testing.T, db *twoFactors) {
  43. // Create a 2FA token
  44. err := db.Create(1, "secure-key", "secure-secret")
  45. if err != nil {
  46. t.Fatal(err)
  47. }
  48. // Get it back and check the Created field
  49. tf, err := db.GetByUserID(1)
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. assert.Equal(t, db.NowFunc().Format(time.RFC3339), tf.Created.UTC().Format(time.RFC3339))
  54. // Verify there are 10 recover codes generated
  55. var count int64
  56. err = db.Model(new(TwoFactorRecoveryCode)).Count(&count).Error
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. assert.Equal(t, int64(10), count)
  61. }
  62. func test_twoFactors_GetByUserID(t *testing.T, db *twoFactors) {
  63. // Create a 2FA token for user 1
  64. err := db.Create(1, "secure-key", "secure-secret")
  65. if err != nil {
  66. t.Fatal(err)
  67. }
  68. // We should be able to get it back
  69. _, err = db.GetByUserID(1)
  70. if err != nil {
  71. t.Fatal(err)
  72. }
  73. // Try to get a non-existent 2FA token
  74. _, err = db.GetByUserID(2)
  75. expErr := ErrTwoFactorNotFound{args: errutil.Args{"userID": int64(2)}}
  76. assert.Equal(t, expErr, err)
  77. }
  78. func test_twoFactors_IsUserEnabled(t *testing.T, db *twoFactors) {
  79. // Create a 2FA token for user 1
  80. err := db.Create(1, "secure-key", "secure-secret")
  81. if err != nil {
  82. t.Fatal(err)
  83. }
  84. assert.True(t, db.IsUserEnabled(1))
  85. assert.False(t, db.IsUserEnabled(2))
  86. }