two_factors.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. package database
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/cockroachdb/errors"
  9. "gorm.io/gorm"
  10. log "unknwon.dev/clog/v2"
  11. "gogs.io/gogs/internal/cryptoutil"
  12. "gogs.io/gogs/internal/errutil"
  13. "gogs.io/gogs/internal/strutil"
  14. )
  15. // BeforeCreate implements the GORM create hook.
  16. func (t *TwoFactor) BeforeCreate(tx *gorm.DB) error {
  17. if t.CreatedUnix == 0 {
  18. t.CreatedUnix = tx.NowFunc().Unix()
  19. }
  20. return nil
  21. }
  22. // AfterFind implements the GORM query hook.
  23. func (t *TwoFactor) AfterFind(_ *gorm.DB) error {
  24. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  25. return nil
  26. }
  27. // TwoFactorsStore is the storage layer for two-factor authentication settings.
  28. type TwoFactorsStore struct {
  29. db *gorm.DB
  30. }
  31. func newTwoFactorsStore(db *gorm.DB) *TwoFactorsStore {
  32. return &TwoFactorsStore{db: db}
  33. }
  34. // Create creates a new 2FA token and recovery codes for given user. The "key"
  35. // is used to encrypt and later decrypt given "secret", which should be
  36. // configured in site-level and change of the "key" will break all existing 2FA
  37. // tokens.
  38. func (s *TwoFactorsStore) Create(ctx context.Context, userID int64, key, secret string) error {
  39. encrypted, err := cryptoutil.AESGCMEncrypt(cryptoutil.MD5Bytes(key), []byte(secret))
  40. if err != nil {
  41. return errors.Wrap(err, "encrypt secret")
  42. }
  43. tf := &TwoFactor{
  44. UserID: userID,
  45. Secret: base64.StdEncoding.EncodeToString(encrypted),
  46. }
  47. recoveryCodes, err := generateRecoveryCodes(userID, 10)
  48. if err != nil {
  49. return errors.Wrap(err, "generate recovery codes")
  50. }
  51. return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  52. err := tx.Create(tf).Error
  53. if err != nil {
  54. return err
  55. }
  56. return tx.Create(&recoveryCodes).Error
  57. })
  58. }
  59. var _ errutil.NotFound = (*ErrTwoFactorNotFound)(nil)
  60. type ErrTwoFactorNotFound struct {
  61. args errutil.Args
  62. }
  63. func IsErrTwoFactorNotFound(err error) bool {
  64. return errors.As(err, &ErrTwoFactorNotFound{})
  65. }
  66. func (err ErrTwoFactorNotFound) Error() string {
  67. return fmt.Sprintf("2FA does not found: %v", err.args)
  68. }
  69. func (ErrTwoFactorNotFound) NotFound() bool {
  70. return true
  71. }
  72. // GetByUserID returns the 2FA token of given user. It returns
  73. // ErrTwoFactorNotFound when not found.
  74. func (s *TwoFactorsStore) GetByUserID(ctx context.Context, userID int64) (*TwoFactor, error) {
  75. tf := new(TwoFactor)
  76. err := s.db.WithContext(ctx).Where("user_id = ?", userID).First(tf).Error
  77. if err != nil {
  78. if errors.Is(err, gorm.ErrRecordNotFound) {
  79. return nil, ErrTwoFactorNotFound{args: errutil.Args{"userID": userID}}
  80. }
  81. return nil, err
  82. }
  83. return tf, nil
  84. }
  85. // IsEnabled returns true if the user has enabled 2FA.
  86. func (s *TwoFactorsStore) IsEnabled(ctx context.Context, userID int64) bool {
  87. var count int64
  88. err := s.db.WithContext(ctx).Model(new(TwoFactor)).Where("user_id = ?", userID).Count(&count).Error
  89. if err != nil {
  90. log.Error("Failed to count two factors [user_id: %d]: %v", userID, err)
  91. }
  92. return count > 0
  93. }
  94. // generateRecoveryCodes generates N number of recovery codes for 2FA.
  95. func generateRecoveryCodes(userID int64, n int) ([]*TwoFactorRecoveryCode, error) {
  96. recoveryCodes := make([]*TwoFactorRecoveryCode, n)
  97. for i := 0; i < n; i++ {
  98. code, err := strutil.RandomChars(10)
  99. if err != nil {
  100. return nil, errors.Wrap(err, "generate random characters")
  101. }
  102. recoveryCodes[i] = &TwoFactorRecoveryCode{
  103. UserID: userID,
  104. Code: strings.ToLower(code[:5] + "-" + code[5:]),
  105. }
  106. }
  107. return recoveryCodes, nil
  108. }