src/EventSubscriber/LogSystem/LogAccessDeniedSubscriber.php line 45

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4.  * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
  5.  *
  6.  * Copyright (C) 2019 - 2020 Jan Böhmer (https://github.com/jbtronics)
  7.  *
  8.  * This program is free software: you can redistribute it and/or modify
  9.  * it under the terms of the GNU Affero General Public License as published
  10.  * by the Free Software Foundation, either version 3 of the License, or
  11.  * (at your option) any later version.
  12.  *
  13.  * This program is distributed in the hope that it will be useful,
  14.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.  * GNU Affero General Public License for more details.
  17.  *
  18.  * You should have received a copy of the GNU Affero General Public License
  19.  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  20.  */
  21. namespace App\EventSubscriber\LogSystem;
  22. use App\Entity\LogSystem\UserNotAllowedLogEntry;
  23. use App\Services\LogSystem\EventLogger;
  24. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  25. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  26. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  27. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  28. /**
  29.  * Write to event log when a user tries to access an forbidden page and recevies an 403 Access Denied message.
  30.  */
  31. class LogAccessDeniedSubscriber implements EventSubscriberInterface
  32. {
  33.     private $logger;
  34.     public function __construct(EventLogger $logger)
  35.     {
  36.         $this->logger $logger;
  37.     }
  38.     public function onKernelException(ExceptionEvent $event): void
  39.     {
  40.         $throwable $event->getThrowable();
  41.         if ($throwable instanceof AccessDeniedHttpException) {
  42.             $throwable $throwable->getPrevious();
  43.         }
  44.         //Ignore everything except AccessDeniedExceptions
  45.         if (!$throwable instanceof AccessDeniedException) {
  46.             return;
  47.         }
  48.         $path $event->getRequest()->getPathInfo();
  49.         $log_entry = new UserNotAllowedLogEntry($path);
  50.         $this->logger->logAndFlush($log_entry);
  51.     }
  52.     public static function getSubscribedEvents()
  53.     {
  54.         return ['kernel.exception' => 'onKernelException'];
  55.     }
  56. }