src/AppBundle/Listener/PermissionKernelControllerListener.php line 31

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Listener;
  3. use Symfony\Component\DependencyInjection\ContainerInterface;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  8. use Symfony\Component\HttpKernel\HttpKernelInterface;
  9. use Topxia\Service\Common\ServiceKernel;
  10. class PermissionKernelControllerListener
  11. {
  12.     protected $paths;
  13.     /**
  14.      * @var ContainerInterface
  15.      */
  16.     private $container;
  17.     /**
  18.      * @var mixed
  19.      */
  20.     private $path;
  21.     public function __construct(ContainerInterface $container$path)
  22.     {
  23.         $this->container $container;
  24.         $this->path $path;
  25.     }
  26.     public function onKernelController(ControllerEvent $event)
  27.     {
  28.         if (HttpKernelInterface::MAIN_REQUEST != $event->getRequestType()) {
  29.             return;
  30.         }
  31.         $request $event->getRequest();
  32.         $currentUser ServiceKernel::instance()->getCurrentUser();
  33.         if (in_array('ROLE_SUPER_ADMIN'$currentUser['roles'])) {
  34.             return;
  35.         }
  36.         $route $this->container
  37.             ->get('router')
  38.             ->getMatcher()
  39.             ->match($request->getPathInfo());
  40.         $permissions = empty($route['_permissions']) ? [] : $route['_permissions'];
  41.         if (empty($permissions)) {
  42.             return;
  43.         }
  44.         foreach ($permissions as $permission) {
  45.             if ($currentUser->hasPermission($permission)) {
  46.                 return;
  47.             }
  48.         }
  49.         if ($this->isApiRequest($request)) {
  50.             $response = new JsonResponse([
  51.                 'status' => false,
  52.                 'message' => $this->container->get('translator')->trans('admin.sensitive_manage.prompt.tips'),
  53.                 'permissions' => (array) $permissions,
  54.             ], 403);
  55.         } elseif (!preg_match('/^\/admin/'$request->getPathInfo())) {
  56.             $response $this->container->get('twig')->render('role/permission-error.html.twig');
  57.         } else {
  58.             $response $this->container->get('twig')->render('admin/role/permission-error.html.twig');
  59.         }
  60.         $event->setController(function () use ($response) {
  61.             return new Response($response403);
  62.         });
  63.     }
  64.     private function isApiRequest(Request $request): bool
  65.     {
  66.         return in_array($request->headers->get('Accept'''), ['application/json''application/vnd.edusoho.v2+json''application/vnd.edusoho.v3+json']);
  67.     }
  68. }