temporary.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package temporary
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "git.ttmylife.com/zeuszhao/kit/buildin"
  7. "git.ttmylife.com/zeuszhao/kit/cache"
  8. "time"
  9. )
  10. var ErrorCode = errors.New("验证码错误")
  11. type VerificationCode struct {
  12. c cache.Cache
  13. key string
  14. }
  15. func NewVerificationCode(c cache.Cache, target string) *VerificationCode {
  16. return &VerificationCode{
  17. c: c,
  18. key: target,
  19. }
  20. }
  21. func (t *VerificationCode) makeKey(target string) string {
  22. return fmt.Sprintf("temporary:auth:code:%s", target)
  23. }
  24. func (t *VerificationCode) Make(ctx context.Context, bit uint8, ti time.Duration) (string, error) {
  25. randStr := buildin.RandNumberString(bit)
  26. k := t.makeKey(t.key)
  27. _, err := t.c.Set(ctx, k, randStr, ti)
  28. if err != nil {
  29. return "", err
  30. }
  31. return randStr, nil
  32. }
  33. func (t *VerificationCode) Verify(ctx context.Context, code string) (bool, error) {
  34. k := t.makeKey(t.key)
  35. vv, err := t.c.Get(ctx, k)
  36. if err != nil {
  37. return false, ErrorCode
  38. }
  39. if vv == code {
  40. return true, nil
  41. }
  42. return false, nil
  43. }
  44. func (t *VerificationCode) Destroy(ctx context.Context) {
  45. k := t.makeKey(t.key)
  46. t.c.Delete(ctx, k)
  47. }