forked from lxh/go-wxhelper
67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
package captcha
|
|
|
|
import (
|
|
"context"
|
|
"gitee.ltd/lxh/logger/log"
|
|
"time"
|
|
"wechat-robot/internal/redis"
|
|
)
|
|
|
|
var ctx = context.Background()
|
|
|
|
type RedisStore struct{}
|
|
|
|
// 验证码缓存前缀
|
|
const cachePrefix = "captcha:img:"
|
|
|
|
// Set
|
|
// @description: 缓存验证码信息
|
|
// @receiver r
|
|
// @param id string 验证码ID
|
|
// @param value string 验证码答案
|
|
// @return error 错误信息
|
|
func (r RedisStore) Set(id string, value string) error {
|
|
key := cachePrefix + id
|
|
err := redis.Client.Set(ctx, key, value, time.Minute).Err()
|
|
if err != nil {
|
|
log.Errorf("写入缓存验证码失败: %v", err.Error())
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Get
|
|
// @description: 获取验证码信息
|
|
// @receiver r
|
|
// @param id string 验证码ID
|
|
// @param clear
|
|
// @return string
|
|
func (r RedisStore) Get(id string, clear bool) string {
|
|
key := cachePrefix + id
|
|
val, err := redis.Client.Get(ctx, key).Result()
|
|
if err != nil {
|
|
log.Errorf("读取缓存验证码失败: %v", err.Error())
|
|
return ""
|
|
}
|
|
if clear {
|
|
err = redis.Client.Del(ctx, key).Err()
|
|
if err != nil {
|
|
log.Errorf("读取缓存验证码失败: %v", err.Error())
|
|
return ""
|
|
}
|
|
}
|
|
return val
|
|
}
|
|
|
|
// Verify
|
|
// @description: 验证验证码
|
|
// @receiver r
|
|
// @param id string 验证码ID
|
|
// @param answer string 验证码答案
|
|
// @param clear bool 是否清除验证码
|
|
// @return bool 是否验证成功
|
|
func (r RedisStore) Verify(id, answer string, clear bool) bool {
|
|
v := r.Get(id, clear)
|
|
return v == answer
|
|
}
|