otp.go 794 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package user
  2. import (
  3. "bytes"
  4. "crypto/sha1"
  5. "encoding/hex"
  6. "github.com/0xJacky/Nginx-UI/internal/crypto"
  7. "github.com/0xJacky/Nginx-UI/model"
  8. "github.com/pkg/errors"
  9. "github.com/pquerna/otp/totp"
  10. )
  11. var (
  12. ErrOTPCode = errors.New("invalid otp code")
  13. ErrRecoveryCode = errors.New("invalid recovery code")
  14. )
  15. func VerifyOTP(user *model.Auth, otp, recoveryCode string) (err error) {
  16. if otp != "" {
  17. decrypted, err := crypto.AesDecrypt(user.OTPSecret)
  18. if err != nil {
  19. return err
  20. }
  21. if ok := totp.Validate(otp, string(decrypted)); !ok {
  22. return ErrOTPCode
  23. }
  24. } else {
  25. recoverCode, err := hex.DecodeString(recoveryCode)
  26. if err != nil {
  27. return err
  28. }
  29. k := sha1.Sum(user.OTPSecret)
  30. if !bytes.Equal(k[:], recoverCode) {
  31. return ErrRecoveryCode
  32. }
  33. }
  34. return
  35. }