// @Summary 登录
// @Tags 登录|退出
// @Accept application/json
// @Produce application/json
// @Param body body model.Auth true "用户名和密码"
// @Success 200
// @Failure 400
// @Failure 500
// @Router /api/auth [post]
func Auth(c *gin.Context) {
var userAuth model.Auth
err := c.ShouldBindJSON(&userAuth)
if err != nil {
response.Error("无效的参数", http.StatusBadRequest, c)
return
}
userId, ok := service.UserAuth(userAuth.Username, userAuth.Passwd)
if !ok {
response.Error("登录失败", http.StatusBadRequest, c)
return
}
roleId := service.UserAuthRoleId(userId)
token, _ := token.GenToken(userAuth.Username, userId, roleId)
responseMap := make(map[string]any)
responseMap[`token`] = token
response.OK(responseMap, c)
}
// @Summary 退出
// @Tags 登录|退出
// @Accept application/json
// @Produce application/json
// @Param Authorization header string true "Bearer 用户令牌"
// @Success 200
// @Failure 400
// @Failure 500
// @Router /api/logout [get]
func Logout(c *gin.Context) {
token := c.GetString(`token`)
if token == "" {
response.Error("请求头中Authorization为空", http.StatusUnauthorized, c)
return
}
ok := service.UserLogout(token)
response.OK(ok, c)
}