update
This commit is contained in:
89
internal/handler/auth_handler.go
Normal file
89
internal/handler/auth_handler.go
Normal file
@ -0,0 +1,89 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"fashionapi/internal/dto"
|
||||
"fashionapi/internal/middleware"
|
||||
"fashionapi/internal/pkg/response"
|
||||
"fashionapi/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// AuthHandler 账号体系接口(JWT 无状态)。
|
||||
type AuthHandler struct {
|
||||
auth service.AuthService
|
||||
}
|
||||
|
||||
// NewAuthHandler 创建账号 handler。
|
||||
func NewAuthHandler(auth service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{auth: auth}
|
||||
}
|
||||
|
||||
// Register 注册。
|
||||
//
|
||||
// POST /api/auth/register
|
||||
// 请求体:{ username, email, password }
|
||||
// 成功:201 { token, user }
|
||||
func (h *AuthHandler) Register(c *gin.Context) {
|
||||
var req dto.AuthRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.auth.Register(c.Request.Context(), req)
|
||||
if err != nil {
|
||||
fail(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, result)
|
||||
}
|
||||
|
||||
// Login 登录。
|
||||
//
|
||||
// POST /api/auth/login
|
||||
// 请求体:{ account, password },account 可填邮箱或用户名
|
||||
// 成功:200 { token, user }
|
||||
func (h *AuthHandler) Login(c *gin.Context) {
|
||||
var req dto.AuthRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalid request")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.auth.Login(c.Request.Context(), req)
|
||||
if err != nil {
|
||||
fail(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
|
||||
// Me 当前登录用户,需 Authorization: Bearer <token>。
|
||||
//
|
||||
// GET /api/auth/me
|
||||
// 成功:200 { user }
|
||||
func (h *AuthHandler) Me(c *gin.Context) {
|
||||
userID, ok := middleware.UserIDFrom(c)
|
||||
if !ok {
|
||||
response.Error(c, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.auth.Me(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
fail(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"user": user})
|
||||
}
|
||||
|
||||
// Logout 登出。
|
||||
//
|
||||
// POST /api/auth/logout
|
||||
// 无状态 JWT 服务端无需作废令牌,由客户端丢弃即可;保留接口以便将来扩展黑名单。
|
||||
func (h *AuthHandler) Logout(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
Reference in New Issue
Block a user