110 lines
2.1 KiB
Go
110 lines
2.1 KiB
Go
package middleware
|
||
|
||
import (
|
||
"net/http"
|
||
|
||
"carrotskin/pkg/auth"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// CasbinMiddleware Casbin权限中间件
|
||
// 需要先经过AuthMiddleware获取用户信息
|
||
func CasbinMiddleware(casbinService *auth.CasbinService, resource, action string) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
// 从上下文获取用户角色(由AuthMiddleware设置)
|
||
role, exists := c.Get("user_role")
|
||
if !exists {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"success": false,
|
||
"message": "未授权访问",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
roleStr, ok := role.(string)
|
||
if !ok || roleStr == "" {
|
||
roleStr = "user" // 默认角色
|
||
}
|
||
|
||
// 检查权限
|
||
if !casbinService.CheckPermission(roleStr, resource, action) {
|
||
c.JSON(http.StatusForbidden, gin.H{
|
||
"success": false,
|
||
"message": "权限不足",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
// RequireAdmin 要求管理员权限的中间件
|
||
func RequireAdmin() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
role, exists := c.Get("user_role")
|
||
if !exists {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"success": false,
|
||
"message": "未授权访问",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
roleStr, ok := role.(string)
|
||
if !ok || roleStr != "admin" {
|
||
c.JSON(http.StatusForbidden, gin.H{
|
||
"success": false,
|
||
"message": "需要管理员权限",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
// RequireRole 要求指定角色的中间件
|
||
func RequireRole(allowedRoles ...string) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
role, exists := c.Get("user_role")
|
||
if !exists {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"success": false,
|
||
"message": "未授权访问",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
roleStr, ok := role.(string)
|
||
if !ok {
|
||
c.JSON(http.StatusForbidden, gin.H{
|
||
"success": false,
|
||
"message": "权限不足",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
// 检查是否在允许的角色列表中
|
||
for _, allowed := range allowedRoles {
|
||
if roleStr == allowed {
|
||
c.Next()
|
||
return
|
||
}
|
||
}
|
||
|
||
c.JSON(http.StatusForbidden, gin.H{
|
||
"success": false,
|
||
"message": "权限不足",
|
||
})
|
||
c.Abort()
|
||
}
|
||
}
|