103 lines
2.5 KiB
Go
103 lines
2.5 KiB
Go
package handler
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/zhilv666/navsite/internal/model"
|
|
"github.com/zhilv666/navsite/internal/service"
|
|
"github.com/zhilv666/navsite/pkg/common"
|
|
"github.com/zhilv666/navsite/pkg/utils"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Req struct {
|
|
Username string `json:"username" binding:"required" example:"admin"`
|
|
Password string `json:"password" binding:"required" example:"123456"`
|
|
OtpCode string `json:"otp_code" example:"123456"`
|
|
}
|
|
|
|
type LoginResp struct {
|
|
Token string `json:"token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ...zYyfQ.bQeIyXvkOExxD4DAy5Eyjgwj9FbjE-AO6FCLF-YFGVA"`
|
|
}
|
|
|
|
// login
|
|
// @Summary 用户登录
|
|
// @Tag Auth
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param login body Req true "登录参数"
|
|
// @Success 200 {object} common.Response[LoginResp] "登录成功"
|
|
// @Failure 400 {object} common.Response[any] "登录失败"
|
|
// @Router /api/v1/auth/login [post]
|
|
func login(c *gin.Context) {
|
|
var req Req
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
common.Fail(c, err.Error())
|
|
return
|
|
}
|
|
user, err := service.GetUserByName(req.Username)
|
|
if err != nil {
|
|
common.Fail(c, err.Error())
|
|
return
|
|
}
|
|
if user == nil {
|
|
common.Fail(c, "账号或密码不正确")
|
|
return
|
|
}
|
|
if len(req.Password) < 32 {
|
|
req.Password = common.Sha1(req.Password)
|
|
}
|
|
if user.Password != req.Password {
|
|
common.Fail(c, "账号或密码不正确")
|
|
return
|
|
}
|
|
token := utils.GenerateJwtToken(user.ID, user.Email, user.SsoID)
|
|
common.Succ(c, LoginResp{Token: token})
|
|
}
|
|
|
|
// register
|
|
// @Summary 用户注册
|
|
// @Tag Auth
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param register body Req true "注册参数"
|
|
// @Success 200 {object} common.Response[Req] "注册成功"
|
|
// @Failure 400 {object} common.Response[any] "注册失败"
|
|
// @Router /api/v1/auth/register [post]
|
|
func register(c *gin.Context) {
|
|
var req Req
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
common.Fail(c, err.Error())
|
|
return
|
|
}
|
|
user, err := service.GetUserByName(req.Username)
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
} else {
|
|
common.Fail(c, "查询用户失败")
|
|
return
|
|
}
|
|
}
|
|
if user != nil {
|
|
common.Fail(c, "该账号已注册")
|
|
return
|
|
}
|
|
if len(req.Password) < 32 {
|
|
req.Password = common.Sha1(req.Password)
|
|
}
|
|
err = service.AddUser(&model.User{
|
|
Username: req.Username,
|
|
Password: req.Password,
|
|
})
|
|
if err != nil {
|
|
common.Fail(c, err.Error())
|
|
return
|
|
}
|
|
common.Ok(c, "账号注册成功")
|
|
}
|
|
|
|
func RegisterRouterAuth(g *gin.RouterGroup) {
|
|
g.POST("/login", login)
|
|
g.POST("/register", register)
|
|
}
|