two_factors.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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/jinzhu/gorm"
  11. "github.com/pkg/errors"
  12. "github.com/t-tiger/gorm-bulk-insert"
  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.
  23. // The "key" is used to encrypt and later decrypt given "secret",
  24. // which should be configured in site-level and change of the "key"
  25. // will break all existing 2FA tokens.
  26. Create(userID int64, key, secret string) error
  27. // GetByUserID returns the 2FA token of given user.
  28. // It returns ErrTwoFactorNotFound when not found.
  29. GetByUserID(userID int64) (*TwoFactor, error)
  30. // IsUserEnabled returns true if the user has enabled 2FA.
  31. IsUserEnabled(userID int64) bool
  32. }
  33. var TwoFactors TwoFactorsStore
  34. // NOTE: This is a GORM create hook.
  35. func (t *TwoFactor) BeforeCreate() {
  36. t.CreatedUnix = gorm.NowFunc().Unix()
  37. }
  38. // NOTE: This is a GORM query hook.
  39. func (t *TwoFactor) AfterFind() {
  40. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  41. }
  42. var _ TwoFactorsStore = (*twoFactors)(nil)
  43. type twoFactors struct {
  44. *gorm.DB
  45. }
  46. func (db *twoFactors) Create(userID int64, key, secret string) error {
  47. encrypted, err := cryptoutil.AESGCMEncrypt(cryptoutil.MD5Bytes(key), []byte(secret))
  48. if err != nil {
  49. return errors.Wrap(err, "encrypt secret")
  50. }
  51. tf := &TwoFactor{
  52. UserID: userID,
  53. Secret: base64.StdEncoding.EncodeToString(encrypted),
  54. }
  55. recoveryCodes, err := generateRecoveryCodes(userID, 10)
  56. if err != nil {
  57. return errors.Wrap(err, "generate recovery codes")
  58. }
  59. records := make([]interface{}, 0, len(recoveryCodes))
  60. for _, code := range recoveryCodes {
  61. records = append(records, code)
  62. }
  63. return db.Transaction(func(tx *gorm.DB) error {
  64. err := tx.Create(tf).Error
  65. if err != nil {
  66. return err
  67. }
  68. return gormbulk.BulkInsert(tx, records, 3000)
  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(userID int64) (*TwoFactor, error) {
  86. tf := new(TwoFactor)
  87. err := db.Where("user_id = ?", userID).First(tf).Error
  88. if err != nil {
  89. if gorm.IsRecordNotFoundError(err) {
  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(userID int64) bool {
  97. var count int64
  98. err := db.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. }