two_factors.go 3.5 KB

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