verification.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package common
  2. import (
  3. "github.com/google/uuid"
  4. "strings"
  5. "sync"
  6. "time"
  7. )
  8. type verificationValue struct {
  9. code string
  10. time time.Time
  11. }
  12. const (
  13. EmailVerificationPurpose = "v"
  14. PasswordResetPurpose = "r"
  15. )
  16. var verificationMutex sync.Mutex
  17. var verificationMap map[string]verificationValue
  18. var verificationMapMaxSize = 10
  19. var VerificationValidMinutes = 10
  20. func GenerateVerificationCode(length int) string {
  21. code := uuid.New().String()
  22. code = strings.Replace(code, "-", "", -1)
  23. if length == 0 {
  24. return code
  25. }
  26. return code[:length]
  27. }
  28. func RegisterVerificationCodeWithKey(key string, code string, purpose string) {
  29. verificationMutex.Lock()
  30. defer verificationMutex.Unlock()
  31. verificationMap[purpose+key] = verificationValue{
  32. code: code,
  33. time: time.Now(),
  34. }
  35. if len(verificationMap) > verificationMapMaxSize {
  36. removeExpiredPairs()
  37. }
  38. }
  39. func VerifyCodeWithKey(key string, code string, purpose string) bool {
  40. verificationMutex.Lock()
  41. defer verificationMutex.Unlock()
  42. value, okay := verificationMap[purpose+key]
  43. now := time.Now()
  44. if !okay || int(now.Sub(value.time).Seconds()) >= VerificationValidMinutes*60 {
  45. return false
  46. }
  47. return code == value.code
  48. }
  49. func DeleteKey(key string, purpose string) {
  50. verificationMutex.Lock()
  51. defer verificationMutex.Unlock()
  52. delete(verificationMap, purpose+key)
  53. }
  54. // no lock inside!
  55. func removeExpiredPairs() {
  56. now := time.Now()
  57. for key := range verificationMap {
  58. if int(now.Sub(verificationMap[key].time).Seconds()) >= VerificationValidMinutes*60 {
  59. delete(verificationMap, key)
  60. }
  61. }
  62. }
  63. func init() {
  64. verificationMutex.Lock()
  65. defer verificationMutex.Unlock()
  66. verificationMap = make(map[string]verificationValue)
  67. }