Files
backend/internal/middleware/casbin.go

123 lines
2.8 KiB
Go
Raw Normal View History

package middleware
import (
"slices"
"strings"
"carrot_bbs/internal/service"
"github.com/gin-gonic/gin"
)
// CasbinAuth Casbin 权限中间件
// 需要在 Auth 中间件之后使用
func CasbinAuth(casbinService service.CasbinService) gin.HandlerFunc {
return func(c *gin.Context) {
// 获取请求路径和方法
path := c.Request.URL.Path
method := c.Request.Method
// 从上下文获取用户ID (由 Auth 中间件设置)
userID, exists := c.Get("user_id")
// 如果用户未登录,检查是否是公开路由
if !exists {
// 对于未登录用户,使用匿名角色检查权限
allowed, err := casbinService.Enforce(c.Request.Context(), "anonymous", path, method)
if err != nil {
c.AbortWithStatusJSON(500, gin.H{
"code": "INTERNAL_ERROR",
"message": "权限检查失败",
})
return
}
if !allowed {
c.AbortWithStatusJSON(401, gin.H{
"code": "UNAUTHORIZED",
"message": "请先登录",
})
return
}
c.Next()
return
}
// 检查用户权限
allowed, err := casbinService.EnforceForUser(c.Request.Context(), userID.(string), path, method)
if err != nil {
c.AbortWithStatusJSON(500, gin.H{
"code": "INTERNAL_ERROR",
"message": "权限检查失败",
})
return
}
if !allowed {
c.AbortWithStatusJSON(403, gin.H{
"code": "FORBIDDEN",
"message": "权限不足",
})
return
}
c.Next()
}
}
// OptionalCasbinAuth 可选的 Casbin 权限检查
// 不阻止请求,但会设置权限标志
func OptionalCasbinAuth(casbinService service.CasbinService) gin.HandlerFunc {
return func(c *gin.Context) {
userID, exists := c.Get("user_id")
if exists {
path := c.Request.URL.Path
method := c.Request.Method
allowed, err := casbinService.EnforceForUser(c.Request.Context(), userID.(string), path, method)
if err == nil {
c.Set("permission_granted", allowed)
}
}
c.Next()
}
}
// RequireRole 要求特定角色的中间件
func RequireRole(casbinService service.CasbinService, requiredRoles ...string) gin.HandlerFunc {
return func(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.AbortWithStatusJSON(401, gin.H{
"code": "UNAUTHORIZED",
"message": "请先登录",
})
return
}
userRoles, err := casbinService.GetRolesForUser(c.Request.Context(), userID.(string))
if err != nil {
c.AbortWithStatusJSON(500, gin.H{
"code": "INTERNAL_ERROR",
"message": "获取用户角色失败",
})
return
}
// 检查用户是否拥有任一所需角色
hasRole := slices.ContainsFunc(requiredRoles, func(required string) bool {
return slices.Contains(userRoles, required)
})
if !hasRole {
c.AbortWithStatusJSON(403, gin.H{
"code": "FORBIDDEN",
"message": "需要以下角色之一: " + strings.Join(requiredRoles, ", "),
})
return
}
c.Next()
}
}