website-nav/component/captcha.go

56 lines
1.1 KiB
Go
Raw Normal View History

2024-10-18 17:19:19 +08:00
package component
import (
"fmt"
"os"
"strings"
"website-nav/global/client"
"website-nav/global/constant"
)
type Captcha struct{}
// Set
// @description: 验证码放入指定存储
// @receiver Captcha
// @param id
// @param value
// @return error
func (Captcha) Set(id string, value string) error {
return client.Cache.Set([]byte(fmt.Sprintf("%s:%s", constant.Captcha, id)), []byte(value), 2*60)
}
// Get
// @description: 获取验证码信息
// @receiver Captcha
// @param id
// @param clear
// @return string
func (Captcha) Get(id string, clear bool) string {
val, err := client.Cache.Get([]byte(fmt.Sprintf("%s:%s", constant.Captcha, id)))
if err != nil {
return ""
}
if clear {
client.Cache.Del([]byte(fmt.Sprintf("%s:%s", constant.Captcha, id)))
return string(val)
}
return string(val)
}
// Verify
// @description: 校验
// @receiver Captcha
// @param id
// @param answer
// @param clear
// @return bool
func (c Captcha) Verify(id, answer string, clear bool) bool {
if os.Getenv("GIN_MODE") != "release" {
return true
}
return strings.ToUpper(answer) == strings.ToUpper(c.Get(id, clear))
}