src/Hitso/Bundle/AdminBundle/EventListener/AccessDeniedListener.php line 60

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Hitso\Bundle\AdminBundle\EventListener;
  4. use Hitso\Bundle\MultiSiteBundle\MultiSite\SiteContext;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Session\Session;
  7. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  8. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  9. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  11. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  12. use Symfony\Contracts\Translation\TranslatorInterface;
  13. class AccessDeniedListener
  14. {
  15.     /**
  16.      * @var SiteContext
  17.      */
  18.     protected $context;
  19.     /**
  20.      * @var AuthorizationCheckerInterface
  21.      */
  22.     protected $checker;
  23.     /**
  24.      * @var TokenStorageInterface
  25.      */
  26.     protected $storage;
  27.     /**
  28.      * @var TranslatorInterface
  29.      */
  30.     protected $translator;
  31.     /**
  32.      * @var UrlGeneratorInterface
  33.      */
  34.     protected $generator;
  35.     public function __construct(
  36.         SiteContext $context,
  37.         AuthorizationCheckerInterface $checker,
  38.         TokenStorageInterface $storage,
  39.         TranslatorInterface $translator,
  40.         UrlGeneratorInterface $generator
  41.     ) {
  42.         $this->context    $context;
  43.         $this->checker    $checker;
  44.         $this->storage    $storage;
  45.         $this->translator $translator;
  46.         $this->generator  $generator;
  47.     }
  48.     public function onException(GetResponseForExceptionEvent $e)
  49.     {
  50.         if (!($e->getException() instanceof AccessDeniedHttpException)) {
  51.             return;
  52.         }
  53.         if (!$this->context->getRunningSite()->isContent() && !$this->checker->isGranted('ROLE_WITH_ACCESS_TO_ADMIN')) {
  54.             $this->storage->setToken(null);
  55.             $session $e->getRequest()->getSession();
  56.             $session->invalidate();
  57.             if ($session instanceof Session) {
  58.                 $session->getFlashBag()->add(
  59.                     'error',
  60.                     $this->translator->trans(
  61.                         'Nie masz uprawnień do logowania się do panelu administracyjnego.',
  62.                         [],
  63.                         'admin'
  64.                     )
  65.                 );
  66.             }
  67.             $e->setResponse(new RedirectResponse($this->generator->generate('hitso_admin_login')));
  68.         }
  69.     }
  70. }