50 lines
1.7 KiB
Go
50 lines
1.7 KiB
Go
|
|
package middleware
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"net/http"
|
|||
|
|
|
|||
|
|
"github.com/gin-gonic/gin"
|
|||
|
|
|
|||
|
|
apperrors "with_you/internal/errors"
|
|||
|
|
"with_you/internal/pkg/auth"
|
|||
|
|
"with_you/internal/pkg/response"
|
|||
|
|
"with_you/internal/service"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// Authorize 基于 Casbin 资源/动作策略的路由级授权中间件。
|
|||
|
|
//
|
|||
|
|
// 用法:挂在 RequireAuth 之后,按路由标注 (resource, action)。
|
|||
|
|
// admin.POST("/users/:id/roles", middleware.Authorize(casbin, "admin/users/roles", "write"), h.AssignRole)
|
|||
|
|
//
|
|||
|
|
// 校验流程:
|
|||
|
|
// 1. 从 context 取出 Principal(由 RequireAuth 写入)。
|
|||
|
|
// 2. 调 CasbinService.EnforceForUser(userID, resource, action)。
|
|||
|
|
// - 内部先查 user_roles 表得到角色集合,再对每个角色调 Enforce(role, resource, action)。
|
|||
|
|
// - super_admin 通过 admin/** 通配策略获得所有 admin 能力。
|
|||
|
|
// 3. 不匹配 → 403 PERMISSION_DENIED。
|
|||
|
|
//
|
|||
|
|
// 纵深防御:service 层对最敏感操作(如分配 super_admin)应再次校验 operator 角色,
|
|||
|
|
// 即使路由 Authorize 漏配,Service 仍能拦截。
|
|||
|
|
func Authorize(casbinService service.CasbinService, resource, action string) gin.HandlerFunc {
|
|||
|
|
return func(c *gin.Context) {
|
|||
|
|
p, ok := auth.GetPrincipal(c)
|
|||
|
|
if !ok || p == nil {
|
|||
|
|
response.ErrorWithStringCode(c, http.StatusUnauthorized, "UNAUTHORIZED", "未授权")
|
|||
|
|
c.Abort()
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
allowed, err := casbinService.EnforceForUser(c.Request.Context(), p.UserID, resource, action)
|
|||
|
|
if err != nil {
|
|||
|
|
response.ErrorWithStringCode(c, http.StatusInternalServerError, "CASBIN_INTERNAL_ERROR", "权限系统内部错误")
|
|||
|
|
c.Abort()
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
if !allowed {
|
|||
|
|
response.ErrorWithStringCode(c, http.StatusForbidden, apperrors.ErrPermissionDenied.Code, apperrors.ErrPermissionDenied.Message)
|
|||
|
|
c.Abort()
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
c.Next()
|
|||
|
|
}
|
|||
|
|
}
|