package handlers import ( "net/http" "github.com/gin-gonic/gin" "github.com/niangaodev/art-code/middleware" "github.com/niangaodev/art-code/models" "github.com/niangaodev/art-code/repositories" "golang.org/x/crypto/bcrypt" ) // AdminLogin 管理员登录 func AdminLogin(c *gin.Context) { var req models.LoginRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"}) return } // 获取用户 user, err := repositories.GetUserByUsername(req.Username) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get user"}) return } if user == nil { c.JSON(http.StatusUnauthorized, gin.H{"error": "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"}) return } // 生成JWT令牌 token, expire, err := middleware.GenerateToken(user.ID, user.Username, user.Role) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"}) return } // 构建响应 response := models.LoginResponse{ Token: token, User: *repositories.BuildUserResponse(user), Expire: expire, } c.JSON(http.StatusOK, response) }