<?php
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;
class AccessDeniedListener implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
// the priority must be greater than the Security HTTP
// ExceptionListener, to make sure it's called before
// the default exception listener
KernelEvents::EXCEPTION => ['onKernelException', 2],
];
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (!$exception instanceof AccessDeniedException) {
return;
}
$routeName = $event->getRequest()->get('_route');
switch ($routeName) {
case 'app_front_library_page':
$accessDeniedMessage = "La modification de vos informations est requise lors de votre première connexion";
break;
default:
$accessDeniedMessage = "Cette ressource n'existe pas !";
break;
}
// $request = $event->getRequest();
// throw new CustomUserMessageAccountStatusException($accessDeniedMessage);
// $request->getSession()->getFlashBag()->add('unauthorized_notice', 'La modification de vos informations est requise lors de votre première connexion.');
// ... perform some action (e.g. logging)
// optionally set the custom response
// $event->setResponse(new Response(null, 403));
// or stop propagation (prevents the next exception listeners from being called)
// $event->stopPropagation();
}
}