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