98 lines
2.5 KiB
Go
98 lines
2.5 KiB
Go
// handlers/auth_handler.go
|
|
package handlers
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"go-todo-api/constants"
|
|
"go-todo-api/dto"
|
|
"go-todo-api/services"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// AuthHandler 依赖于 AuthService 接口
|
|
type AuthHandler struct {
|
|
Service services.AuthService
|
|
}
|
|
|
|
// NewAuthHandler 创建 AuthHandler 的新实例
|
|
func NewAuthHandler(service services.AuthService) *AuthHandler {
|
|
return &AuthHandler{Service: service}
|
|
}
|
|
|
|
// RegisterHandler 处理 POST /register 请求
|
|
func (h *AuthHandler) RegisterHandler(c *gin.Context) {
|
|
var input dto.RegisterInput
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, constants.StandardResponse{
|
|
Code: constants.CodeValidationError,
|
|
Message: "Invalid input format or missing fields",
|
|
})
|
|
return
|
|
}
|
|
|
|
newUser, err := h.Service.Register(&input)
|
|
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "username already taken") { // 检查 Service 返回的特定错误
|
|
c.JSON(http.StatusConflict, constants.StandardResponse{
|
|
Code: constants.CodeConflictError,
|
|
Message: "Username already taken",
|
|
})
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, constants.StandardResponse{
|
|
Code: constants.CodeInternalError,
|
|
Message: "Failed to register user",
|
|
})
|
|
return
|
|
}
|
|
|
|
// 注册成功,返回脱敏信息
|
|
c.JSON(http.StatusCreated, constants.StandardResponse{
|
|
Code: constants.CodeSuccess,
|
|
Message: "User created successfully",
|
|
Data: newUser,
|
|
})
|
|
}
|
|
|
|
// LoginHandler 处理 POST /login 请求
|
|
func (h *AuthHandler) LoginHandler(c *gin.Context) {
|
|
var input dto.LoginInput
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, constants.StandardResponse{
|
|
Code: constants.CodeValidationError,
|
|
Message: "Invalid input format or missing fields",
|
|
})
|
|
return
|
|
}
|
|
|
|
token, err := h.Service.Login(&input)
|
|
|
|
if err != nil {
|
|
// 统一处理登录失败,防止泄露细节
|
|
if errors.Is(err, errors.New("invalid username or password")) {
|
|
c.JSON(http.StatusUnauthorized, constants.StandardResponse{
|
|
Code: constants.CodeInvalidAuth,
|
|
Message: "Invalid username or password",
|
|
})
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, constants.StandardResponse{
|
|
Code: constants.CodeInternalError,
|
|
Message: "Failed to login",
|
|
})
|
|
return
|
|
}
|
|
|
|
// 登录成功,返回令牌
|
|
c.JSON(http.StatusOK, constants.StandardResponse{
|
|
Code: constants.CodeSuccess,
|
|
Message: "Login successful!",
|
|
Data: token,
|
|
})
|
|
}
|