|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Pterodactyl\Http\Middleware\API; |
| 4 | + |
| 5 | +use Closure; |
| 6 | +use Illuminate\Http\Request; |
| 7 | +use Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface; |
| 8 | +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
| 9 | +use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; |
| 10 | + |
| 11 | +class HasPermissionToResource |
| 12 | +{ |
| 13 | + /** |
| 14 | + * @var \Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface |
| 15 | + */ |
| 16 | + private $repository; |
| 17 | + |
| 18 | + /** |
| 19 | + * HasPermissionToResource constructor. |
| 20 | + * |
| 21 | + * @param \Pterodactyl\Contracts\Repository\ApiKeyRepositoryInterface $repository |
| 22 | + */ |
| 23 | + public function __construct(ApiKeyRepositoryInterface $repository) |
| 24 | + { |
| 25 | + $this->repository = $repository; |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Determine if an API key has permission to access the given route. |
| 30 | + * |
| 31 | + * @param \Illuminate\Http\Request $request |
| 32 | + * @param \Closure $next |
| 33 | + * @param string $role |
| 34 | + * @return mixed |
| 35 | + */ |
| 36 | + public function handle(Request $request, Closure $next, string $role = 'admin') |
| 37 | + { |
| 38 | + /** @var \Pterodactyl\Models\APIKey $model */ |
| 39 | + $model = $request->attributes->get('api_key'); |
| 40 | + |
| 41 | + if ($role === 'admin' && ! $request->user()->root_admin) { |
| 42 | + throw new NotFoundHttpException; |
| 43 | + } |
| 44 | + |
| 45 | + $this->repository->loadPermissions($model); |
| 46 | + $routeKey = str_replace(['api.', 'admin.'], '', $request->route()->getName()); |
| 47 | + |
| 48 | + $count = $model->getRelation('permissions')->filter(function ($permission) use ($routeKey) { |
| 49 | + return $routeKey === str_replace('-', '.', $permission->permission); |
| 50 | + })->count(); |
| 51 | + |
| 52 | + if ($count === 1) { |
| 53 | + return $next($request); |
| 54 | + } |
| 55 | + |
| 56 | + throw new AccessDeniedHttpException('Cannot access resource without required `' . $routeKey . '` permission.'); |
| 57 | + } |
| 58 | +} |
0 commit comments