Files
X-Agents/server/internal/handler/auth_handler.go
DESKTOP-72TV0V4\caoxiaozhu 51a1202168 feat: 添加用户认证模块
- main.go: 初始化 User/Role 模型、UserRepository、AuthService 和 AuthHandler
- 添加 /auth/register、/auth/login、/auth/me 路由
- auth_handler.go: 新增 GetCurrentUser 接口获取当前用户信息
- .gitignore: 添加 .bitfun/ 目录忽略

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 10:25:50 +08:00

105 lines
2.4 KiB
Go

package handler
import (
"net/http"
"x-agents/server/internal/service"
"github.com/gin-gonic/gin"
)
type AuthHandler struct {
authService *service.AuthService
}
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
return &AuthHandler{authService: authService}
}
type LoginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
type LoginResponse struct {
Token string `json:"token"`
User interface{} `json:"user"`
}
// Login 处理登录
func (h *AuthHandler) Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
resp, err := h.authService.Login(service.LoginRequest{
Username: req.Username,
Password: req.Password,
})
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, LoginResponse{
Token: resp.Token,
User: gin.H{
"id": resp.User.ID,
"username": resp.User.Username,
"email": resp.User.Email,
"role": resp.User.RoleID,
},
})
}
// Register 处理注册
func (h *AuthHandler) Register(c *gin.Context) {
var req struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
Email string `json:"email"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
user, err := h.authService.Register(req.Username, req.Password, req.Email)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, gin.H{
"id": user.ID,
"username": user.Username,
"email": user.Email,
})
}
// GetCurrentUser 获取当前登录用户信息
func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "user not found in context"})
return
}
user, err := h.authService.GetUserByID(userID.(string))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
c.JSON(http.StatusOK, gin.H{
"id": user.ID,
"username": user.Username,
"email": user.Email,
"role_id": user.RoleID,
"is_active": user.IsActive,
"created_at": user.CreatedAt,
})
}