Files
2026-04-28 10:29:02 +08:00

117 lines
3.1 KiB
Go

package system
import (
"sundynix-go/global"
"sundynix-go/model/commom/response"
"sundynix-go/model/system"
systemReq "sundynix-go/model/system/request"
systemRes "sundynix-go/model/system/response"
"sundynix-go/utils/jwt"
"github.com/gin-gonic/gin"
"github.com/mojocn/base64Captcha"
"go.uber.org/zap"
)
var store = base64Captcha.DefaultMemStore
type AuthApi struct{}
// Login
// @Tags 登录相关
// @Summary pc登录
// @accept application/json
// @Produce application/json
// @Param data body systemReq.Login true "用户名, 密码, 验证码,验证码id"
// @Success 200 {object} response.Response{msg=string} "登录成功"
// @Router /api/auth/login [post]
func (a *AuthApi) Login(c *gin.Context) {
var l systemReq.Login
err := c.ShouldBindJSON(&l)
if err != nil {
response.FailWithMsg(err.Error(), c)
return
}
// 验证码校验:enable-captcha=0 时跳过
captchaOk := global.Config.System.EnableCaptcha == 0 ||
(l.CaptchaId != "" && l.Captcha != "" && store.Verify(l.CaptchaId, l.Captcha, true))
if !captchaOk {
response.FailWithMsg("验证码错误", c)
return
}
u := &system.User{Account: l.Account, Password: l.Password}
user, err := userService.Login(u)
if err != nil {
global.Logger.Error("登录失败! 用户名不存在或者密码错误!", zap.Error(err))
response.FailWithMsg("用户名不存在或者密码错误", c)
return
}
a.GetToken(c, *user)
}
// Logout
// @Tags 登录相关
// @Summary pc登出
// @Security BasicAuth
// @Produce application/json
// @Success 200 {object} response.Response{msg=string} "登出成功"
// @Router /api/auth/logout [get]
func (a *AuthApi) Logout(c *gin.Context) {
token := jwt.GetToken(c)
userId := jwt.GetUserId(c)
err := jwtService.PutBlacklist(userId, token)
if err != nil {
global.Logger.Error("登出失败!", zap.Error(err))
response.FailWithMsg("登出失败", c)
return
}
jwt.ClearToken(c)
response.OkWithMsg("登出成功", c)
}
// Captcha
// @Tags 登录相关
// @Summary 获取验证码
// @Produce application/json
// @Success 200 {object} response.Response{data=systemRes.CaptchaRes} "获取验证码"
// @Router /api/auth/captcha [get]
func (u *AuthApi) Captcha(c *gin.Context) {
var driver = base64Captcha.DriverString{
Height: 80,
Width: 240,
NoiseCount: 2,
ShowLineOptions: 4,
Length: 4,
Source: "1234567890",
}
cp := base64Captcha.NewCaptcha(&driver, store)
id, b64s, _, err := cp.Generate()
if err != nil {
global.Logger.Error("GenerateCaptcha err", zap.Error(err))
response.FailWithMsg("GenerateCaptcha err", c)
return
}
response.OkWithData(systemRes.CaptchaRes{
CaptchaId: id,
Captcha: b64s,
}, c)
}
func (a *AuthApi) GetToken(c *gin.Context, user system.User) {
token, claims, err := jwt.GetLoginToken(&user)
if err != nil {
global.Logger.Error("GetToken err", zap.Error(err))
response.FailWithMsg("GetToken err", c)
}
response.OkWithData(systemRes.LoginResponse{
ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
Token: token,
User: user,
}, c)
}