zhangqian
2023-08-14 676ef551324d415ed5280166407c686481c6f51f
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package v1
 
import (
    "apsClient/conf"
    "apsClient/constvar"
    "apsClient/model"
    "apsClient/model/request"
    _ "apsClient/model/response"
    "apsClient/pkg/contextx"
    "apsClient/pkg/convertx"
    "apsClient/pkg/ecode"
    "apsClient/pkg/logx"
    "apsClient/service"
    "github.com/gin-gonic/gin"
    "github.com/mojocn/base64Captcha"
    "time"
)
 
// 当开启多服务器部署时,替换下面的配置,使用redis共享存储验证码
// var store = captcha.NewDefaultRedisStore()
var (
    store       = base64Captcha.DefaultMemStore
    userService = &service.UserService{}
)
 
type UserApi struct{}
 
// Login
// @Tags      Base
// @Summary   用户登录
// @Produce   application/json
// @Param     object  body    request.Login true  "查询参数"
// @Success   200   {object}  contextx.Response{data=response.LoginResponse}  "成功"
// @Router    /api/base/login [post]
func (slf *UserApi) Login(c *gin.Context) {
    var params request.Login
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
 
    // 判断验证码是否开启
    key := c.ClientIP()
    openCaptcha := conf.Conf.Captcha.OpenCaptcha               // 是否开启防爆次数
    openCaptchaTimeOut := conf.Conf.Captcha.OpenCaptchaTimeOut // 缓存超时时间
    v, ok := constvar.BlackCache.Get(key)
    if !ok {
        constvar.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
    }
 
    var oc bool = openCaptcha == 0 || convertx.InterfaceToInt(v) > openCaptcha // 0 表示每次登录都需要验证码 或者当前次数已超过防爆次数
 
    if !oc || store.Verify(params.CaptchaId, params.Captcha, true) {
        u := &model.User{Username: params.Username, Password: params.Password}
        user, errCode := userService.Login(u)
        if errCode != ecode.OK {
            logx.Errorf("登陆失败! 用户名不存在或者密码错误! errCode:%v", errCode)
            // 验证码次数+1
            _ = constvar.BlackCache.Increment(key, 1)
            ctx.Fail(errCode)
            return
        }
        if !user.Enable {
            logx.Errorf("登陆失败! 用户被禁止登录!")
            // 验证码次数+1
            _ = constvar.BlackCache.Increment(key, 1)
            ctx.Fail(ecode.UserForbidden)
            return
        }
        return
    }
 
    // 验证码次数+1
    _ = constvar.BlackCache.Increment(key, 1)
    ctx.Fail(ecode.CaptchaErr)
}