79 lines
1.7 KiB
Go
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()
|
||
|
|
})
|
||
|
|
}
|