[bugfix/backend] use roles in middleware

This commit is contained in:
CDN 2025-02-21 05:58:42 +08:00
parent e5fc8691bf
commit 287895347b
Signed by: CDN
GPG key ID: 0C656827F9F80080
2 changed files with 61 additions and 42 deletions

View file

@ -100,20 +100,30 @@ func AuthMiddleware(jwtSecret string, tokenBlacklist *service.TokenBlacklist) gi
return
}
// 设置用户 ID
c.Set("user_id", userIDStr)
// 设置用户角色
if role, ok := claims["role"].(string); ok {
log.Debug().Str("role", role).Msg("Found user role")
c.Set("user_role", role)
} else {
log.Error().Interface("role", claims["role"]).Msg("Invalid or missing role claim")
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid role format"})
// 获取用户角色
roles, exists := claims["roles"]
if !exists {
log.Error().Msg("Token does not contain roles claim")
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token format: missing roles"})
c.Abort()
return
}
// 将角色转换为字符串数组
var roleNames []string
if rolesArray, ok := roles.([]interface{}); ok {
for _, r := range rolesArray {
if roleStr, ok := r.(string); ok {
roleNames = append(roleNames, roleStr)
}
}
}
// 设置上下文
c.Set("user_id", userIDStr)
c.Set("user_roles", roleNames) // 存储角色数组
c.Next()
return
} else {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
@ -125,27 +135,37 @@ func AuthMiddleware(jwtSecret string, tokenBlacklist *service.TokenBlacklist) gi
// RoleMiddleware creates a middleware for role-based authorization
func RoleMiddleware(roles ...string) gin.HandlerFunc {
return func(c *gin.Context) {
userRole, exists := c.Get("user_role")
userRoles, exists := c.Get("user_roles")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "User role not found"})
log.Error().Msg("User roles not found in context")
c.JSON(http.StatusUnauthorized, gin.H{"error": "User roles not found"})
c.Abort()
return
}
roleStr, ok := userRole.(string)
roleNames, ok := userRoles.([]string)
if !ok {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid user role type"})
log.Error().Msg("Invalid user roles type")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid user roles type"})
c.Abort()
return
}
for _, role := range roles {
if role == roleStr {
c.Next()
return
// 检查用户是否拥有任一所需角色
for _, requiredRole := range roles {
for _, userRole := range roleNames {
if requiredRole == userRole {
c.Next()
return
}
}
}
log.Warn().
Strs("required_roles", roles).
Strs("user_roles", roleNames).
Msg("Insufficient permissions")
c.JSON(http.StatusForbidden, gin.H{"error": "Insufficient permissions"})
c.Abort()
}