2026-05-24 13:14:41 +08:00
|
|
|
package handler
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
|
|
"gen2d/internal/model"
|
2026-05-24 13:53:03 +08:00
|
|
|
"gen2d/internal/service"
|
2026-05-24 13:14:41 +08:00
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
)
|
|
|
|
|
|
2026-05-24 13:53:03 +08:00
|
|
|
var authSvc *service.AuthService
|
|
|
|
|
|
|
|
|
|
// InitAuthService 由 main 在启动时调用,注入 JWT 配置。
|
|
|
|
|
func InitAuthService(jwtSecret string, jwtExpire int64) {
|
|
|
|
|
authSvc = service.NewAuthService(jwtSecret, jwtExpire)
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-24 13:14:41 +08:00
|
|
|
// RegisterRequest 注册请求参数。
|
|
|
|
|
type RegisterRequest struct {
|
2026-05-24 13:53:03 +08:00
|
|
|
Username string `json:"username" binding:"required,min=3,max=32"`
|
|
|
|
|
Password string `json:"password" binding:"required,min=6,max=64"`
|
|
|
|
|
Email string `json:"email" binding:"omitempty,email"`
|
2026-05-24 13:14:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// RegisterResponse 注册成功返回的用户信息。
|
|
|
|
|
type RegisterResponse struct {
|
|
|
|
|
ID uint `json:"id"`
|
|
|
|
|
Username string `json:"username"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Register 用户注册接口,创建新用户账号。
|
|
|
|
|
func Register(c *gin.Context) {
|
|
|
|
|
var req RegisterRequest
|
|
|
|
|
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
|
|
|
user, err := authSvc.Register(c.Request.Context(), req.Username, req.Password, req.Email)
|
|
|
|
|
if err != nil {
|
|
|
|
|
c.JSON(http.StatusConflict, model.Fail(http.StatusConflict, err.Error()))
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-24 13:14:41 +08:00
|
|
|
c.JSON(http.StatusCreated, model.OK(RegisterResponse{
|
2026-05-24 13:53:03 +08:00
|
|
|
ID: user.ID,
|
|
|
|
|
Username: user.Username,
|
2026-05-24 13:14:41 +08:00
|
|
|
}))
|
|
|
|
|
}
|