two_factor.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. // Copyright 2017 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. "time"
  9. "github.com/pquerna/otp/totp"
  10. "github.com/unknwon/com"
  11. "gogs.io/gogs/internal/conf"
  12. "gogs.io/gogs/internal/cryptoutil"
  13. )
  14. // TwoFactor is a 2FA token of a user.
  15. type TwoFactor struct {
  16. ID int64
  17. UserID int64 `xorm:"UNIQUE" gorm:"UNIQUE"`
  18. Secret string
  19. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  20. CreatedUnix int64
  21. }
  22. // ValidateTOTP returns true if given passcode is valid for two-factor authentication token.
  23. // It also returns possible validation error.
  24. func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
  25. secret, err := base64.StdEncoding.DecodeString(t.Secret)
  26. if err != nil {
  27. return false, fmt.Errorf("DecodeString: %v", err)
  28. }
  29. decryptSecret, err := com.AESGCMDecrypt(cryptoutil.MD5Bytes(conf.Security.SecretKey), secret)
  30. if err != nil {
  31. return false, fmt.Errorf("AESGCMDecrypt: %v", err)
  32. }
  33. return totp.Validate(passcode, string(decryptSecret)), nil
  34. }
  35. // DeleteTwoFactor removes two-factor authentication token and recovery codes of given user.
  36. func DeleteTwoFactor(userID int64) (err error) {
  37. sess := x.NewSession()
  38. defer sess.Close()
  39. if err = sess.Begin(); err != nil {
  40. return err
  41. }
  42. if _, err = sess.Where("user_id = ?", userID).Delete(new(TwoFactor)); err != nil {
  43. return fmt.Errorf("delete two-factor: %v", err)
  44. } else if err = deleteRecoveryCodesByUserID(sess, userID); err != nil {
  45. return fmt.Errorf("deleteRecoveryCodesByUserID: %v", err)
  46. }
  47. return sess.Commit()
  48. }
  49. // TwoFactorRecoveryCode represents a two-factor authentication recovery code.
  50. type TwoFactorRecoveryCode struct {
  51. ID int64
  52. UserID int64
  53. Code string `xorm:"VARCHAR(11)"`
  54. IsUsed bool
  55. }
  56. // GetRecoveryCodesByUserID returns all recovery codes of given user.
  57. func GetRecoveryCodesByUserID(userID int64) ([]*TwoFactorRecoveryCode, error) {
  58. recoveryCodes := make([]*TwoFactorRecoveryCode, 0, 10)
  59. return recoveryCodes, x.Where("user_id = ?", userID).Find(&recoveryCodes)
  60. }
  61. func deleteRecoveryCodesByUserID(e Engine, userID int64) error {
  62. _, err := e.Where("user_id = ?", userID).Delete(new(TwoFactorRecoveryCode))
  63. return err
  64. }
  65. // RegenerateRecoveryCodes regenerates new set of recovery codes for given user.
  66. func RegenerateRecoveryCodes(userID int64) error {
  67. recoveryCodes, err := generateRecoveryCodes(userID, 10)
  68. if err != nil {
  69. return fmt.Errorf("generateRecoveryCodes: %v", err)
  70. }
  71. sess := x.NewSession()
  72. defer sess.Close()
  73. if err = sess.Begin(); err != nil {
  74. return err
  75. }
  76. if err = deleteRecoveryCodesByUserID(sess, userID); err != nil {
  77. return fmt.Errorf("deleteRecoveryCodesByUserID: %v", err)
  78. } else if _, err = sess.Insert(recoveryCodes); err != nil {
  79. return fmt.Errorf("insert new recovery codes: %v", err)
  80. }
  81. return sess.Commit()
  82. }
  83. type ErrTwoFactorRecoveryCodeNotFound struct {
  84. Code string
  85. }
  86. func IsTwoFactorRecoveryCodeNotFound(err error) bool {
  87. _, ok := err.(ErrTwoFactorRecoveryCodeNotFound)
  88. return ok
  89. }
  90. func (err ErrTwoFactorRecoveryCodeNotFound) Error() string {
  91. return fmt.Sprintf("two-factor recovery code does not found [code: %s]", err.Code)
  92. }
  93. // UseRecoveryCode validates recovery code of given user and marks it is used if valid.
  94. func UseRecoveryCode(userID int64, code string) error {
  95. recoveryCode := new(TwoFactorRecoveryCode)
  96. has, err := x.Where("code = ?", code).And("is_used = ?", false).Get(recoveryCode)
  97. if err != nil {
  98. return fmt.Errorf("get unused code: %v", err)
  99. } else if !has {
  100. return ErrTwoFactorRecoveryCodeNotFound{Code: code}
  101. }
  102. recoveryCode.IsUsed = true
  103. if _, err = x.Id(recoveryCode.ID).Cols("is_used").Update(recoveryCode); err != nil {
  104. return fmt.Errorf("mark code as used: %v", err)
  105. }
  106. return nil
  107. }