94 lines
2.0 KiB
Go
94 lines
2.0 KiB
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"goblog/handlers"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
"github.com/golang-jwt/jwt/v5"
|
||
|
|
)
|
||
|
|
|
||
|
|
// JWT 认证中间件
|
||
|
|
func JWTAuth() gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
authHeader := c.GetHeader("Authorization")
|
||
|
|
if authHeader == "" {
|
||
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "缺少认证令牌"})
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
parts := strings.SplitN(authHeader, " ", 2)
|
||
|
|
if !(len(parts) == 2 && parts[0] == "Bearer") {
|
||
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "认证格式错误"})
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
tokenString := parts[1]
|
||
|
|
claims := &handlers.Claims{}
|
||
|
|
|
||
|
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||
|
|
return handlers.JWTSecret(), nil
|
||
|
|
})
|
||
|
|
|
||
|
|
if err != nil || !token.Valid {
|
||
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的令牌"})
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
c.Set("userID", claims.UserID)
|
||
|
|
c.Set("username", claims.Username)
|
||
|
|
c.Set("role", claims.Role)
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 管理员权限中间件
|
||
|
|
func AdminRequired() gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
role, exists := c.Get("role")
|
||
|
|
if !exists || role != "admin" {
|
||
|
|
c.JSON(http.StatusForbidden, gin.H{"error": "需要管理员权限"})
|
||
|
|
c.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 可选认证中间件(用于某些既支持游客又支持登录用户的接口)
|
||
|
|
func OptionalAuth() gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
authHeader := c.GetHeader("Authorization")
|
||
|
|
if authHeader == "" {
|
||
|
|
c.Next()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
parts := strings.SplitN(authHeader, " ", 2)
|
||
|
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
||
|
|
c.Next()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
tokenString := parts[1]
|
||
|
|
claims := &handlers.Claims{}
|
||
|
|
|
||
|
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||
|
|
return handlers.JWTSecret(), nil
|
||
|
|
})
|
||
|
|
|
||
|
|
if err == nil && token.Valid {
|
||
|
|
c.Set("userID", claims.UserID)
|
||
|
|
c.Set("username", claims.Username)
|
||
|
|
c.Set("role", claims.Role)
|
||
|
|
}
|
||
|
|
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|