1 Star 0 Fork 0

Cruvie Kang / kk_go_kit

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
kk_captcha.go 1.97 KB
一键复制 编辑 原始数据 按行查看 历史
Cruvie 提交于 2024-01-26 18:01 . update log
package kk_captcha
import (
"gitee.com/cruvie/kk_go_kit/kk_db/kk_redis"
"gitee.com/cruvie/kk_go_kit/kk_stage"
"github.com/mojocn/base64Captcha"
"log/slog"
"strings"
"time"
)
// redisStore 由于服务器是负载均衡,所以需要用redis来替代默认的store 如果是单台服务器,不需要redis来管理
type redisStore struct {
expiration time.Duration
}
const (
RedisPrefixCaptcha = "Captcha:"
)
func (rs *redisStore) Set(id string, value string) error {
key := RedisPrefixCaptcha + id
//转换成小写存进redis
err := kk_redis.Set(key, strings.ToLower(value), rs.expiration)
if err != nil {
slog.Error("unable to set captcha to redis", kk_stage.NewLog(nil).Error(err).Args()...)
return err
}
return nil
}
func (rs *redisStore) Get(id string, clear bool) string {
key := RedisPrefixCaptcha + id
code, err := kk_redis.Get(key)
if err != nil {
slog.Error("unable to get captcha from redis", kk_stage.NewLog(nil).Error(err).Args()...)
return ""
}
if clear {
err := kk_redis.Del(key)
if err != nil {
slog.Error("unable to delete captcha in redis", kk_stage.NewLog(nil).Error(err).Args()...)
}
}
return code
}
func (rs *redisStore) Verify(id string, answer string, clear bool) bool {
v := rs.Get(id, clear)
return v == strings.ToLower(answer)
}
func newRedisStore(expiration time.Duration) base64Captcha.Store {
s := new(redisStore)
s.expiration = expiration
return s
}
// 过期时间2分钟
var store = newRedisStore(2 * time.Minute)
// GenerateCaptcha 验证码生成
func GenerateCaptcha(stage *kk_stage.Stage) (id string, b64s string) {
driver := mathConfig()
// 创建验证码并传入创建的类型的配置,以及存储的对象
c := base64Captcha.NewCaptcha(driver, store)
id, b64s, _, err := c.Generate()
if err != nil {
slog.Error("generate captcha failed", kk_stage.NewLog(stage).Error(err).Args()...)
return
}
return id, b64s
}
func VerifyCaptcha(id string, answer string) (res bool) {
return store.Verify(id, answer, true)
}
1
https://gitee.com/cruvie/kk_go_kit.git
git@gitee.com:cruvie/kk_go_kit.git
cruvie
kk_go_kit
kk_go_kit
8ab331d8547b

搜索帮助