BUG修复,返回结构统一

This commit is contained in:
李琦
2026-01-16 17:03:34 +08:00
parent 87ed11db7a
commit e6edf7210b
57 changed files with 3642 additions and 1074 deletions

View File

@@ -1,54 +1,102 @@
package handlers
import (
"net/http"
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/niangaodev/art-code/middleware"
"github.com/niangaodev/art-code/config"
"github.com/niangaodev/art-code/models"
"github.com/niangaodev/art-code/repositories"
"golang.org/x/crypto/bcrypt"
"github.com/niangaodev/art-code/utils"
)
// AdminLogin 管理员登录
func AdminLogin(c *gin.Context) {
var req models.LoginRequest
// Login 请求结构
type LoginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
// Login 登录
func Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
utils.Error(c, 400, "Invalid request")
return
}
// 获取用户
user, err := repositories.GetUserByUsername(req.Username)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get user"})
utils.ServerError(c, err)
return
}
if user == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username or password"})
utils.Error(c, 401, "Invalid username or password")
return
}
// 验证密码
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username or password"})
if !utils.CheckPasswordHash(req.Password, user.Password) {
utils.Error(c, 401, "Invalid username or password")
return
}
// 生成JWT令牌
token, expire, err := middleware.GenerateToken(user.ID, user.Username, user.Role)
// 生成JWT Token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"userID": user.ID,
"exp": time.Now().Add(time.Hour * 24).Unix(), // 24小时过期
})
tokenString, err := token.SignedString([]byte(config.JWTSecret))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"})
utils.ServerError(c, err)
return
}
// 构建响应
response := models.LoginResponse{
Token: token,
User: *repositories.BuildUserResponse(user),
Expire: expire,
// 记录登录日志
go func() {
ip := c.ClientIP()
location := utils.GetRegion(ip)
logEntry := &models.UserAccessLog{
UserID: user.ID,
UserIP: ip,
UserLocation: location,
}
if err := repositories.CreateUserAccessLog(logEntry); err != nil {
fmt.Printf("Failed to create login log: %v\n", err)
}
}()
utils.Success(c, gin.H{
"token": tokenString,
"user": gin.H{
"id": user.ID,
"username": user.Username,
"email": user.Email,
"role": user.Role,
},
})
}
// GetCurrentUser 获取当前用户信息
func GetCurrentUser(c *gin.Context) {
userID, exists := c.Get("userID")
if !exists {
utils.Error(c, 401, "Unauthorized")
return
}
c.JSON(http.StatusOK, response)
user, err := repositories.GetUserByID(userID.(uint))
if err != nil {
utils.ServerError(c, err)
return
}
if user == nil {
utils.Error(c, 404, "User not found")
return
}
utils.Success(c, repositories.BuildUserResponse(user))
}