update permission middleware

This commit is contained in:
2026-03-12 14:04:32 +08:00
parent 5c28488bc5
commit 6ff5320ace
3 changed files with 326 additions and 5 deletions
@@ -12,6 +12,7 @@ use App\Service\ScopeBitmapService;
use App\Service\ScopeTableManager;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\HttpServer\Router\Dispatched;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
@@ -33,7 +34,7 @@ class PermissionMiddleware implements MiddlewareInterface
// 获取已认证用户(由 AuthMiddleware 预先认证)
$user = $this->auth->guard('jwt')->user();
if (!$user) {
return $handler->handle($request);
return $this->forbiddenResponse('用户认证异常');
}
// 获取用户 scope(含角色和 bitmap
@@ -44,11 +45,14 @@ class PermissionMiddleware implements MiddlewareInterface
$role = $user_scope['role'];
$method = $request->getMethod();
$path = $request->getUri()->getPath();
// 通过 Dispatched 获取路由模板路径(如 /api/v1/users/{id}),解决参数化路由匹配问题
$dispatched = $request->getAttribute(Dispatched::class);
$route_path = $dispatched?->handler?->route ?? $request->getUri()->getPath();
// ===== Step 1: 路由访问检查 =====
if ($role !== 'administrator') {
$access_result = $this->checkRouteAccess($user->role_id, $method, $path);
$access_result = $this->checkRouteAccess($user->role_id, $method, $route_path);
if ($access_result === false) {
return $this->forbiddenResponse('无权访问该接口');
}
@@ -76,8 +80,8 @@ class PermissionMiddleware implements MiddlewareInterface
// 查找路由记录
$route = Route::query()->where('method', $method)->where('path', $path)->first();
if (!$route) {
// 未注册到 routes 表的路由默认放行
return true;
// 白名单模式:未注册到 routes 表的路由拒绝访问
return false;
}
// 1. 先查 override(优先级最高)