2026-05-24 13:14:41 +08:00
|
|
|
package handler
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
|
|
"gen2d/internal/model"
|
|
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// LoginRequest 登录请求参数。
|
|
|
|
|
type LoginRequest struct {
|
2026-05-24 13:53:03 +08:00
|
|
|
Username string `json:"username" binding:"required"`
|
|
|
|
|
Password string `json:"password" binding:"required"`
|
2026-05-24 13:14:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// LoginResponse 登录成功返回的凭证及用户信息。
|
|
|
|
|
type LoginResponse struct {
|
2026-05-24 13:53:03 +08:00
|
|
|
Token string `json:"token"`
|
|
|
|
|
ExpiresIn int64 `json:"expiresIn"`
|
|
|
|
|
User model.User `json:"user"`
|
2026-05-24 13:14:41 +08:00
|
|
|
}
|
|
|
|
|
|
2026-05-24 13:53:03 +08:00
|
|
|
// Login 用户登录接口,校验用户名/密码并返回 JWT 令牌。
|
2026-05-24 13:14:41 +08:00
|
|
|
func Login(c *gin.Context) {
|
|
|
|
|
var req LoginRequest
|
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
|
|
|
c.JSON(http.StatusBadRequest, model.Fail(http.StatusBadRequest, "参数错误: "+err.Error()))
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-24 13:53:03 +08:00
|
|
|
token, expiresIn, user, err := authSvc.Login(c.Request.Context(), req.Username, req.Password)
|
|
|
|
|
if err != nil {
|
|
|
|
|
c.JSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, err.Error()))
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-24 13:14:41 +08:00
|
|
|
c.JSON(http.StatusOK, model.OK(LoginResponse{
|
2026-05-24 13:53:03 +08:00
|
|
|
Token: token,
|
|
|
|
|
ExpiresIn: expiresIn,
|
|
|
|
|
User: *user,
|
2026-05-24 13:14:41 +08:00
|
|
|
}))
|
|
|
|
|
}
|