You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

twofactor.go 3.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. // Copyright 2017 The Gitea 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 models
  5. import (
  6. "crypto/md5"
  7. "crypto/subtle"
  8. "encoding/base64"
  9. "time"
  10. "github.com/Unknwon/com"
  11. "github.com/go-xorm/xorm"
  12. "github.com/pquerna/otp/totp"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/setting"
  15. )
  16. // TwoFactor represents a two-factor authentication token.
  17. type TwoFactor struct {
  18. ID int64 `xorm:"pk autoincr"`
  19. UID int64 `xorm:"UNIQUE"`
  20. Secret string
  21. ScratchToken string
  22. Created time.Time `xorm:"-"`
  23. CreatedUnix int64 `xorm:"INDEX created"`
  24. Updated time.Time `xorm:"-"` // Note: Updated must below Created for AfterSet.
  25. UpdatedUnix int64 `xorm:"INDEX updated"`
  26. }
  27. // AfterSet is invoked from XORM after setting the value of a field of this object.
  28. func (t *TwoFactor) AfterSet(colName string, _ xorm.Cell) {
  29. switch colName {
  30. case "created_unix":
  31. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  32. case "updated_unix":
  33. t.Updated = time.Unix(t.UpdatedUnix, 0).Local()
  34. }
  35. }
  36. // GenerateScratchToken recreates the scratch token the user is using.
  37. func (t *TwoFactor) GenerateScratchToken() error {
  38. token, err := base.GetRandomString(8)
  39. if err != nil {
  40. return err
  41. }
  42. t.ScratchToken = token
  43. return nil
  44. }
  45. // VerifyScratchToken verifies if the specified scratch token is valid.
  46. func (t *TwoFactor) VerifyScratchToken(token string) bool {
  47. if len(token) == 0 {
  48. return false
  49. }
  50. return subtle.ConstantTimeCompare([]byte(token), []byte(t.ScratchToken)) == 1
  51. }
  52. func (t *TwoFactor) getEncryptionKey() []byte {
  53. k := md5.Sum([]byte(setting.SecretKey))
  54. return k[:]
  55. }
  56. // SetSecret sets the 2FA secret.
  57. func (t *TwoFactor) SetSecret(secret string) error {
  58. secretBytes, err := com.AESEncrypt(t.getEncryptionKey(), []byte(secret))
  59. if err != nil {
  60. return err
  61. }
  62. t.Secret = base64.StdEncoding.EncodeToString(secretBytes)
  63. return nil
  64. }
  65. // ValidateTOTP validates the provided passcode.
  66. func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
  67. decodedStoredSecret, err := base64.StdEncoding.DecodeString(t.Secret)
  68. if err != nil {
  69. return false, err
  70. }
  71. secret, err := com.AESDecrypt(t.getEncryptionKey(), decodedStoredSecret)
  72. if err != nil {
  73. return false, err
  74. }
  75. secretStr := string(secret)
  76. return totp.Validate(passcode, secretStr), nil
  77. }
  78. // NewTwoFactor creates a new two-factor authentication token.
  79. func NewTwoFactor(t *TwoFactor) error {
  80. err := t.GenerateScratchToken()
  81. if err != nil {
  82. return err
  83. }
  84. _, err = x.Insert(t)
  85. return err
  86. }
  87. // UpdateTwoFactor updates a two-factor authentication token.
  88. func UpdateTwoFactor(t *TwoFactor) error {
  89. _, err := x.Id(t.ID).AllCols().Update(t)
  90. return err
  91. }
  92. // GetTwoFactorByUID returns the two-factor authentication token associated with
  93. // the user, if any.
  94. func GetTwoFactorByUID(uid int64) (*TwoFactor, error) {
  95. twofa := &TwoFactor{UID: uid}
  96. has, err := x.Get(twofa)
  97. if err != nil {
  98. return nil, err
  99. } else if !has {
  100. return nil, ErrTwoFactorNotEnrolled{uid}
  101. }
  102. return twofa, nil
  103. }
  104. // DeleteTwoFactorByID deletes two-factor authentication token by given ID.
  105. func DeleteTwoFactorByID(id, userID int64) error {
  106. cnt, err := x.Id(id).Delete(&TwoFactor{
  107. UID: userID,
  108. })
  109. if err != nil {
  110. return err
  111. } else if cnt != 1 {
  112. return ErrTwoFactorNotEnrolled{userID}
  113. }
  114. return nil
  115. }