Files
sundynix-go/api/v1/system/auth.go
T
2025-09-15 21:00:39 +08:00

93 lines
2.3 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 api
func (a *AuthApi) Login(c *gin.Context) {
var l systemReq.Login
err := c.ShouldBindJSON(&l)
if err != nil {
response.FailWithMsg(err.Error(), c)
return
}
if l.CaptchaId != "" && l.Captcha != "" && store.Verify(l.CaptchaId, l.Captcha, true) {
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)
return
}
response.FailWithMsg("验证码错误", c)
}
// 登出
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 api 生成验证码
func (u *AuthApi) Captcha(c *gin.Context) {
var driver = base64Captcha.DriverString{
Height: 80,
Width: 240,
NoiseCount: 2,
ShowLineOptions: 4,
Length: 4,
Source: "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM",
}
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)
}