Files
backend/internal/middleware/auth.go
lafay b23a169925
All checks were successful
Build / build (push) Successful in 7m17s
Build / build-docker (push) Successful in 2m41s
chore: import 分组规范 + 文档同步 + config 修复
2026-06-15 16:52:20 +08:00

80 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 (
"net/http"
"strings"
"carrotskin/internal/model"
"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("user_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("user_role", claims.Role)
}
}
}
c.Next()
})
}