Files
backend/internal/middleware/casbin.go
lafay 7d1c78f965
Some checks failed
Build / build (push) Successful in 7m52s
Build / build-docker (push) Has been cancelled
refactor: 移除全局单例、修复分层违规、统一错误与响应
2026-06-15 16:40:36 +08:00

118 lines
2.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package middleware
import (
"net/http"
"carrotskin/internal/model"
"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, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
c.Abort()
return
}
roleStr, ok := role.(string)
if !ok || roleStr == "" {
roleStr = "user" // 默认角色
}
// 检查权限
if !casbinService.CheckPermission(roleStr, resource, action) {
c.JSON(http.StatusForbidden, model.NewErrorResponse(
model.CodeForbidden,
model.MsgForbidden,
nil,
))
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, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
c.Abort()
return
}
roleStr, ok := role.(string)
if !ok || roleStr != "admin" {
c.JSON(http.StatusForbidden, model.NewErrorResponse(
model.CodeForbidden,
"需要管理员权限",
nil,
))
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, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
c.Abort()
return
}
roleStr, ok := role.(string)
if !ok {
c.JSON(http.StatusForbidden, model.NewErrorResponse(
model.CodeForbidden,
model.MsgForbidden,
nil,
))
c.Abort()
return
}
// 检查是否在允许的角色列表中
for _, allowed := range allowedRoles {
if roleStr == allowed {
c.Next()
return
}
}
c.JSON(http.StatusForbidden, model.NewErrorResponse(
model.CodeForbidden,
model.MsgForbidden,
nil,
))
c.Abort()
}
}