3 Star 0 Fork 0

neuro-netw0rk/server-golib

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
captcha.go 2.28 KB
一键复制 编辑 原始数据 按行查看 历史
LeoWang 提交于 2024-12-16 16:45 +08:00 . 整合golib和serverlib
package captcha
import (
"context"
"gitee.com/neuro-netw0rk/server-golib/errors"
dcaptcha "github.com/dchest/captcha"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v7"
)
type Value struct {
ID string `json:"id,omitempty"`
Code string `json:"code,omitempty"`
Img string `json:"img,omitempty"`
Len int `json:"len,omitempty"`
}
type Captcha struct {
enabled bool
options Options
imgExt string
}
type Options struct {
Enabled bool
StoreMode int8
Len int
Width int
Height int
Rds *redis.Client
}
type StoreMode int8
const (
defaultStoreMode = storeModeMem
storeModeMem = 0
storeModeRedis = 1
)
const defaultImgExt = ".png"
const defaultLen = 4
var (
ErrNotEnabled = errors.New("captcha: not enabled")
ErrIDEmpty = errors.New("captcha: id is empty")
)
var C *Captcha
func Init(opts *Options) {
if opts == nil {
return
}
if !opts.Enabled {
return
}
if opts.Rds == nil {
opts.StoreMode = defaultStoreMode
}
if opts.StoreMode != storeModeMem && opts.StoreMode != storeModeRedis {
opts.StoreMode = defaultStoreMode
}
if opts.StoreMode == storeModeRedis {
dcaptcha.SetCustomStore(newRedisMode(context.Background(), opts.Rds))
}
if opts.Width <= 0 {
opts.Width = dcaptcha.StdWidth
}
if opts.Height <= 0 {
opts.Height = dcaptcha.StdHeight
}
if opts.Len <= 0 {
opts.Len = defaultLen
}
C = &Captcha{
enabled: true,
options: *opts,
imgExt: defaultImgExt,
}
}
func (c *Captcha) GetEnabled() bool {
if c == nil {
return false
}
return c.enabled
}
// Get 获取验证码
func (c *Captcha) Get() *Value {
if !c.GetEnabled() {
return &Value{}
}
id := dcaptcha.NewLen(c.options.Len)
return &Value{
ID: id,
Code: "",
Img: id + c.imgExt,
Len: c.options.Len,
}
}
// Verify 验证验证码
func (c *Captcha) Verify(val *Value) bool {
if !c.GetEnabled() {
return true
}
if val == nil {
return false
}
if val.ID == "" || val.Code == "" {
return false
}
return dcaptcha.VerifyString(val.ID, val.Code)
}
// Show 展示验证码
func (c *Captcha) Show(ctx *gin.Context, id string) error {
if !c.GetEnabled() {
return ErrNotEnabled
}
if id == "" {
return ErrIDEmpty
}
err := dcaptcha.WriteImage(ctx.Writer, id, c.options.Width, c.options.Height)
if err != nil {
return err
}
return nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/neuro-netw0rk/server-golib.git
git@gitee.com:neuro-netw0rk/server-golib.git
neuro-netw0rk
server-golib
server-golib
v0.0.5-beta2

搜索帮助