totp.go 554 B

12345678910111213141516171819202122
  1. package totp
  2. import (
  3. "time"
  4. "github.com/xlzd/gotp"
  5. )
  6. // SkewWindows is how many 30s steps around now VerifyWithSkew accepts.
  7. // Standard TOTP clock-drift tolerance, see MHSanaei/3x-ui#6535.
  8. const SkewWindows = 1
  9. // VerifyWithSkew accepts the code for the current step plus/minus SkewWindows.
  10. func VerifyWithSkew(secret, code string, now time.Time) bool {
  11. totp := gotp.NewDefaultTOTP(secret)
  12. for i := -SkewWindows; i <= SkewWindows; i++ {
  13. if totp.AtTime(now.Add(time.Duration(i*30)*time.Second)) == code {
  14. return true
  15. }
  16. }
  17. return false
  18. }