. */ namespace App\EventSubscriber\LogSystem; use App\Entity\LogSystem\UserNotAllowedLogEntry; use App\Services\LogSystem\EventLogger; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\Security\Core\Exception\AccessDeniedException; /** * Write to event log when a user tries to access an forbidden page and recevies an 403 Access Denied message. */ class LogAccessDeniedSubscriber implements EventSubscriberInterface { private $logger; public function __construct(EventLogger $logger) { $this->logger = $logger; } public function onKernelException(ExceptionEvent $event): void { $throwable = $event->getThrowable(); if ($throwable instanceof AccessDeniedHttpException) { $throwable = $throwable->getPrevious(); } //Ignore everything except AccessDeniedExceptions if (! $throwable instanceof AccessDeniedException) { return; } $path = $event->getRequest()->getPathInfo(); $log_entry = new UserNotAllowedLogEntry($path); $this->logger->logAndFlush($log_entry); } public static function getSubscribedEvents() { return ['kernel.exception' => 'onKernelException']; } }