83 lines
2.1 KiB
Go
83 lines
2.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"
|
|
|
|
"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) {
|
|
utils.ClearToken(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 := utils.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)
|
|
}
|