Files
gemini-banlancer/internal/handlers/api_auth_handler.go
2025-11-20 12:24:05 +08:00

51 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Filename: internal/handlers/api_auth_handler.go
package handlers
import (
"gemini-balancer/internal/middleware"
"gemini-balancer/internal/service"
"net/http"
"github.com/gin-gonic/gin"
)
type APIAuthHandler struct {
securityService *service.SecurityService
}
func NewAPIAuthHandler(securityService *service.SecurityService) *APIAuthHandler {
return &APIAuthHandler{securityService: securityService}
}
type LoginRequest struct {
Token string `json:"token" binding:"required"`
}
type LoginResponse struct {
Token string `json:"token"`
Message string `json:"message"`
}
func (h *APIAuthHandler) HandleLogin(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式错误: " + err.Error()})
return
}
authToken, err := h.securityService.AuthenticateToken(req.Token)
// 同时检查token是否有效以及是否是管理员
if err != nil || !authToken.IsAdmin {
h.securityService.RecordFailedLoginAttempt(c.Request.Context(), c.ClientIP())
c.JSON(http.StatusUnauthorized, gin.H{"error": "无效或非管理员Token"})
return
}
middleware.SetAdminSessionCookie(c, authToken.Token)
c.JSON(http.StatusOK, LoginResponse{
Token: authToken.Token,
Message: "登录成功,欢迎管理员!",
})
}