<?php
declare(strict_types=1);
namespace Hitso\Bundle\AdminBundle\EventListener;
use Hitso\Bundle\MultiSiteBundle\MultiSite\SiteContext;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class AccessDeniedListener
{
/**
* @var SiteContext
*/
protected $context;
/**
* @var AuthorizationCheckerInterface
*/
protected $checker;
/**
* @var TokenStorageInterface
*/
protected $storage;
/**
* @var TranslatorInterface
*/
protected $translator;
/**
* @var UrlGeneratorInterface
*/
protected $generator;
public function __construct(
SiteContext $context,
AuthorizationCheckerInterface $checker,
TokenStorageInterface $storage,
TranslatorInterface $translator,
UrlGeneratorInterface $generator
) {
$this->context = $context;
$this->checker = $checker;
$this->storage = $storage;
$this->translator = $translator;
$this->generator = $generator;
}
public function onException(GetResponseForExceptionEvent $e)
{
if (!($e->getException() instanceof AccessDeniedHttpException)) {
return;
}
if (!$this->context->getRunningSite()->isContent() && !$this->checker->isGranted('ROLE_WITH_ACCESS_TO_ADMIN')) {
$this->storage->setToken(null);
$session = $e->getRequest()->getSession();
$session->invalidate();
if ($session instanceof Session) {
$session->getFlashBag()->add(
'error',
$this->translator->trans(
'Nie masz uprawnień do logowania się do panelu administracyjnego.',
[],
'admin'
)
);
}
$e->setResponse(new RedirectResponse($this->generator->generate('hitso_admin_login')));
}
}
}