123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- package temporary
- import (
- "context"
- "errors"
- "fmt"
- "git.ttmylife.com/zeuszhao/kit/buildin"
- "git.ttmylife.com/zeuszhao/kit/cache"
- "time"
- )
- var ErrorCode = errors.New("验证码错误")
- type VerificationCode struct {
- c cache.Cache
- key string
- }
- func NewVerificationCode(c cache.Cache, target string) *VerificationCode {
- return &VerificationCode{
- c: c,
- key: target,
- }
- }
- func (t *VerificationCode) makeKey(target string) string {
- return fmt.Sprintf("temporary:auth:code:%s", target)
- }
- func (t *VerificationCode) Make(ctx context.Context, bit uint8, ti time.Duration) (string, error) {
- randStr := buildin.RandNumberString(bit)
- k := t.makeKey(t.key)
- _, err := t.c.Set(ctx, k, randStr, ti)
- if err != nil {
- return "", err
- }
- return randStr, nil
- }
- func (t *VerificationCode) Verify(ctx context.Context, code string) (bool, error) {
- k := t.makeKey(t.key)
- vv, err := t.c.Get(ctx, k)
- if err != nil {
- return false, ErrorCode
- }
- if vv == code {
- return true, nil
- }
- return false, nil
- }
- func (t *VerificationCode) Destroy(ctx context.Context) {
- k := t.makeKey(t.key)
- t.c.Delete(ctx, k)
- }
|