wangpengfei
2023-07-26 e0a433e9c31594527a3bf7766c0bfb2cbbceffdb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package v1
 
import (
    "aps_crm/conf"
    "aps_crm/constvar"
    "aps_crm/model/response"
    "aps_crm/pkg/contextx"
    "aps_crm/pkg/convertx"
    "aps_crm/pkg/ecode"
    "aps_crm/pkg/logx"
    "github.com/gin-gonic/gin"
    "github.com/mojocn/base64Captcha"
    "time"
)
 
type BaseApi struct{}
 
// Captcha
//    @Tags        Base
//    @Summary    获取验证码
//    @Produce    application/json
//    @Success    200    {object}    contextx.Response{data=response.LoginResponse}    "成功"
//    @Router        /api/base/captcha [post]
func (slf *BaseApi) Captcha(c *gin.Context) {
    ctx, ok := contextx.NewContext(c, nil)
    if !ok {
        return
    }
 
    // 判断验证码是否开启
    openCaptcha := conf.Conf.Captcha.OpenCaptcha               // 是否开启防爆次数
    openCaptchaTimeOut := conf.Conf.Captcha.OpenCaptchaTimeOut // 缓存超时时间
    key := c.ClientIP()
    v, ok := constvar.BlackCache.Get(key)
    if !ok {
        constvar.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
    }
 
    var oc bool
    if openCaptcha == 0 || convertx.InterfaceToInt(v) > openCaptcha { // 0 表示每次登录都需要验证码 或者当前次数已超过防爆次数
        oc = true
    }
    // 字符,公式,验证码配置
    // 生成默认数字的driver
    driver := base64Captcha.NewDriverDigit(conf.Conf.Captcha.ImgHeight, conf.Conf.Captcha.ImgWidth, conf.Conf.Captcha.KeyLong, 0.7, 80)
    cp := base64Captcha.NewCaptcha(driver, store)
    id, b64s, err := cp.Generate()
    captcha := store.Get(id, false)
    logx.Infof("Captcha Generate captchaId:%v captcha:%v", id, captcha)
    if err != nil {
        logx.Errorf("Captcha Generate err:%v", err)
        ctx.Fail(ecode.CaptchaGenerateFailed)
        return
    }
 
    ctx.OkWithDetailed(response.CaptchaResponse{
        CaptchaId:     id,
        PicPath:       b64s,
        CaptchaLength: conf.Conf.Captcha.KeyLong,
        OpenCaptcha:   oc,
    })
}