Files
Message-Push-Nest/routers/api/auth.go
T

58 lines
1.3 KiB
Go
Raw Normal View History

2023-12-30 17:40:20 +08:00
package api
import (
2024-01-01 13:09:44 +08:00
"fmt"
2023-12-30 17:40:20 +08:00
"net/http"
"github.com/gin-gonic/gin"
"message-nest/pkg/app"
"message-nest/pkg/e"
"message-nest/pkg/util"
"message-nest/service/auth_service"
)
type auth struct {
Username string `valid:"Required; MaxSize(50)"`
Password string `valid:"Required; MaxSize(50)"`
}
type ReqAuth struct {
2024-01-01 13:09:44 +08:00
Username string `json:"username" validate:"required,max=36" label:"用户名"`
Password string `json:"passwd" validate:"required,max=36" label:"密码"`
2023-12-30 17:40:20 +08:00
}
func GetAuth(c *gin.Context) {
2024-01-01 13:09:44 +08:00
var (
appG = app.Gin{C: c}
req ReqAuth
)
add
errCode, errMsg := app.BindJsonAndPlayValid(c, &req)
if errCode != e.SUCCESS {
appG.CResponse(errCode, errMsg, nil)
2023-12-30 17:40:20 +08:00
return
}
2024-01-01 13:09:44 +08:00
authService := auth_service.Auth{Username: req.Username, Password: req.Password}
2023-12-30 17:40:20 +08:00
isExist, err := authService.Check()
if err != nil {
2024-01-01 13:09:44 +08:00
appG.CResponse(http.StatusInternalServerError, fmt.Sprintf("校验失败:%s", err), nil)
2023-12-30 17:40:20 +08:00
return
}
if !isExist {
2024-01-01 13:09:44 +08:00
appG.CResponse(http.StatusUnauthorized, "账号或密码不正确!", nil)
2023-12-30 17:40:20 +08:00
return
}
2024-01-01 13:09:44 +08:00
token, err := util.GenerateToken(req.Username, req.Password)
2023-12-30 17:40:20 +08:00
if err != nil {
2024-01-01 13:09:44 +08:00
appG.CResponse(http.StatusInternalServerError, fmt.Sprintf("生成token失败:%s", err), nil)
2023-12-30 17:40:20 +08:00
return
}
2024-01-01 13:09:44 +08:00
appG.CResponse(http.StatusOK, "登录成功!", map[string]string{
2023-12-30 17:40:20 +08:00
"token": token,
})
}