two_factors.go 3.7 KB

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