Files
backend/internal/middleware/auth.go
lan 0bcd9336c4 refactor: Update service and repository methods to use context
- Refactored multiple service and repository methods to accept context as a parameter, enhancing consistency and enabling better control over request lifecycles.
- Updated handlers to utilize context in method calls, improving error handling and performance.
- Cleaned up Dockerfile by removing unnecessary whitespace.
2025-12-03 15:27:12 +08:00

79 lines
1.8 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.

package middleware
import (
"carrotskin/internal/model"
"net/http"
"strings"
"carrotskin/pkg/auth"
"github.com/gin-gonic/gin"
)
// AuthMiddleware JWT认证中间件注入JWT服务版本
func AuthMiddleware(jwtService *auth.JWTService) gin.HandlerFunc {
return gin.HandlerFunc(func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
"缺少Authorization头",
nil,
))
c.Abort()
return
}
// Bearer token格式
tokenParts := strings.SplitN(authHeader, " ", 2)
if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
"无效的Authorization头格式",
nil,
))
c.Abort()
return
}
token := tokenParts[1]
claims, err := jwtService.ValidateToken(token)
if err != nil {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
"无效的token",
err,
))
c.Abort()
return
}
// 将用户信息存储到上下文中
c.Set("user_id", claims.UserID)
c.Set("username", claims.Username)
c.Set("role", claims.Role)
c.Next()
})
}
// OptionalAuthMiddleware 可选的JWT认证中间件注入JWT服务版本
func OptionalAuthMiddleware(jwtService *auth.JWTService) gin.HandlerFunc {
return gin.HandlerFunc(func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader != "" {
tokenParts := strings.SplitN(authHeader, " ", 2)
if len(tokenParts) == 2 && tokenParts[0] == "Bearer" {
token := tokenParts[1]
claims, err := jwtService.ValidateToken(token)
if err == nil {
c.Set("user_id", claims.UserID)
c.Set("username", claims.Username)
c.Set("role", claims.Role)
}
}
}
c.Next()
})
}