otp.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package user
  2. import (
  3. "bytes"
  4. "crypto/sha1"
  5. "encoding/hex"
  6. "fmt"
  7. "github.com/0xJacky/Nginx-UI/internal/cache"
  8. "github.com/0xJacky/Nginx-UI/internal/crypto"
  9. "github.com/0xJacky/Nginx-UI/model"
  10. "github.com/google/uuid"
  11. "github.com/pquerna/otp/totp"
  12. "time"
  13. )
  14. func VerifyOTP(user *model.User, otp, recoveryCode string) (err error) {
  15. if otp != "" {
  16. decrypted, err := crypto.AesDecrypt(user.OTPSecret)
  17. if err != nil {
  18. return err
  19. }
  20. if ok := totp.Validate(otp, string(decrypted)); !ok {
  21. return ErrOTPCode
  22. }
  23. } else {
  24. recoverCode, err := hex.DecodeString(recoveryCode)
  25. if err != nil {
  26. return err
  27. }
  28. k := sha1.Sum(user.OTPSecret)
  29. if !bytes.Equal(k[:], recoverCode) {
  30. return ErrRecoveryCode
  31. }
  32. }
  33. return
  34. }
  35. func secureSessionIDCacheKey(sessionId string) string {
  36. return fmt.Sprintf("2fa_secure_session:_%s", sessionId)
  37. }
  38. func SetSecureSessionID(userId uint64) (sessionId string) {
  39. sessionId = uuid.NewString()
  40. cache.Set(secureSessionIDCacheKey(sessionId), userId, 5*time.Minute)
  41. return
  42. }
  43. func VerifySecureSessionID(sessionId string, userId uint64) bool {
  44. if v, ok := cache.Get(secureSessionIDCacheKey(sessionId)); ok {
  45. if v.(uint64) == userId {
  46. return true
  47. }
  48. }
  49. return false
  50. }