<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
/**
* Access Control Listener
*/
final class ControlListener
{
/** @var RouterInterface $router */
private $router;
/** @var Security $security */
private $security;
public function __construct(RouterInterface $router, Security $security)
{
$this->router = $router;
$this->security = $security;
}
public function onAccessController(RequestEvent $event)
{
$request = $event->getRequest();
$routeCollec = $this->router->getRouteCollection();
$token = $this->security->getToken();
// https://symfony.com/doc/current/routing.html#getting-the-route-name-and-parameters
$routeName = $request->attributes->get('_route');
$activeRoute = $routeCollec->get($routeName ?? '');
$securedRoute = false; // Verification pour la présence ou non en session du activeStructure
if ($activeRoute) {
$roles = $activeRoute->getRequirements();
if (isset($roles['role'])) {
if (false === $this->security->isGranted($roles['role'])) {
throw new AccessDeniedException();
}
}
// Tokens instances implementing the getFirewallName method
if (!(
$token instanceof PreAuthenticatedToken
|| $token instanceof RememberMeToken
|| $token instanceof UsernamePasswordToken
)) {
return;
}
if ('factuwall' === $token->getFirewallName()
&& $activeRoute->getPath() != '/' && $activeRoute->getPath() != '/structure/set/'
) {
$securedRoute = true;
}
if ($securedRoute === true && !$request->getSession()->get('activeStructure')) {
$url = $this->router->generate('factu_homepage');
$event->setResponse(new RedirectResponse($url));
}
}
}
}