two_factors.go 3.7 KB

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