Files
backend/internal/middleware/auth.go
lan 4b4980820f
Some checks failed
SonarQube Analysis / sonarqube (push) Has been cancelled
Test / test (push) Has been cancelled
Test / lint (push) Has been cancelled
Test / build (push) Has been cancelled
chore: 初始化仓库,排除二进制文件和覆盖率文件
2025-11-28 23:30:49 +08:00

79 lines
1.7 KiB
Go

package middleware
import (
"net/http"
"strings"
"carrotskin/pkg/auth"
"github.com/gin-gonic/gin"
)
// AuthMiddleware JWT认证中间件
func AuthMiddleware() gin.HandlerFunc {
return gin.HandlerFunc(func(c *gin.Context) {
jwtService := auth.MustGetJWTService()
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"code": 401,
"message": "缺少Authorization头",
})
c.Abort()
return
}
// Bearer token格式
tokenParts := strings.SplitN(authHeader, " ", 2)
if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
c.JSON(http.StatusUnauthorized, gin.H{
"code": 401,
"message": "无效的Authorization头格式",
})
c.Abort()
return
}
token := tokenParts[1]
claims, err := jwtService.ValidateToken(token)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"code": 401,
"message": "无效的token",
})
c.Abort()
return
}
// 将用户信息存储到上下文中
c.Set("user_id", claims.UserID)
c.Set("username", claims.Username)
c.Set("role", claims.Role)
c.Next()
})
}
// OptionalAuthMiddleware 可选的JWT认证中间件
func OptionalAuthMiddleware() gin.HandlerFunc {
return gin.HandlerFunc(func(c *gin.Context) {
jwtService := auth.MustGetJWTService()
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()
})
}