two_factors.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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. 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() {
  35. t.CreatedUnix = gorm.NowFunc().Unix()
  36. }
  37. // NOTE: This is a GORM query hook.
  38. func (t *TwoFactor) AfterFind() {
  39. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  40. }
  41. var _ TwoFactorsStore = (*twoFactors)(nil)
  42. type twoFactors struct {
  43. *gorm.DB
  44. }
  45. func (db *twoFactors) Create(userID int64, key, secret string) error {
  46. encrypted, err := cryptoutil.AESGCMEncrypt(cryptoutil.MD5Bytes(key), []byte(secret))
  47. if err != nil {
  48. return errors.Wrap(err, "encrypt secret")
  49. }
  50. tf := &TwoFactor{
  51. UserID: userID,
  52. Secret: base64.StdEncoding.EncodeToString(encrypted),
  53. }
  54. recoveryCodes, err := generateRecoveryCodes(userID, 10)
  55. if err != nil {
  56. return errors.Wrap(err, "generate recovery codes")
  57. }
  58. vals := make([]string, 0, len(recoveryCodes))
  59. items := make([]interface{}, 0, len(recoveryCodes)*2)
  60. for _, code := range recoveryCodes {
  61. vals = append(vals, "(?, ?)")
  62. items = append(items, code.UserID, code.Code)
  63. }
  64. return db.Transaction(func(tx *gorm.DB) error {
  65. err := tx.Create(tf).Error
  66. if err != nil {
  67. return err
  68. }
  69. sql := "INSERT INTO two_factor_recovery_code (user_id, code) VALUES " + strings.Join(vals, ", ")
  70. return tx.Exec(sql, items...).Error
  71. })
  72. }
  73. var _ errutil.NotFound = (*ErrTwoFactorNotFound)(nil)
  74. type ErrTwoFactorNotFound struct {
  75. args errutil.Args
  76. }
  77. func IsErrTwoFactorNotFound(err error) bool {
  78. _, ok := err.(ErrTwoFactorNotFound)
  79. return ok
  80. }
  81. func (err ErrTwoFactorNotFound) Error() string {
  82. return fmt.Sprintf("2FA does not found: %v", err.args)
  83. }
  84. func (ErrTwoFactorNotFound) NotFound() bool {
  85. return true
  86. }
  87. func (db *twoFactors) GetByUserID(userID int64) (*TwoFactor, error) {
  88. tf := new(TwoFactor)
  89. err := db.Where("user_id = ?", userID).First(tf).Error
  90. if err != nil {
  91. if gorm.IsRecordNotFoundError(err) {
  92. return nil, ErrTwoFactorNotFound{args: errutil.Args{"userID": userID}}
  93. }
  94. return nil, err
  95. }
  96. return tf, nil
  97. }
  98. func (db *twoFactors) IsUserEnabled(userID int64) bool {
  99. var count int64
  100. err := db.Model(new(TwoFactor)).Where("user_id = ?", userID).Count(&count).Error
  101. if err != nil {
  102. log.Error("Failed to count two factors [user_id: %d]: %v", userID, err)
  103. }
  104. return count > 0
  105. }
  106. // generateRecoveryCodes generates N number of recovery codes for 2FA.
  107. func generateRecoveryCodes(userID int64, n int) ([]*TwoFactorRecoveryCode, error) {
  108. recoveryCodes := make([]*TwoFactorRecoveryCode, n)
  109. for i := 0; i < n; i++ {
  110. code, err := strutil.RandomChars(10)
  111. if err != nil {
  112. return nil, errors.Wrap(err, "generate random characters")
  113. }
  114. recoveryCodes[i] = &TwoFactorRecoveryCode{
  115. UserID: userID,
  116. Code: strings.ToLower(code[:5] + "-" + code[5:]),
  117. }
  118. }
  119. return recoveryCodes, nil
  120. }