src/EventSubscriber/NotAuthorizedResponseSubscriber.php line 43

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use App\Entity\System\Employee;
  5. use App\Service\AdminRouteSecurityService;
  6. use App\Service\EnvironmentService;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\Routing\RouterInterface;
  13. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  14. use Symfony\Component\Security\Core\Security;
  15. class NotAuthorizedResponseSubscriber implements EventSubscriberInterface
  16. {
  17.     private RouterInterface $router;
  18.     private Security $security;
  19.     private EnvironmentService $environmentService;
  20.     private AdminRouteSecurityService $adminRouteSecurityService;
  21.     public function __construct(
  22.         RouterInterface $router,
  23.         Security $security,
  24.         EnvironmentService $environmentService,
  25.         AdminRouteSecurityService $adminRouteSecurityService
  26.     ) {
  27.         $this->router $router;
  28.         $this->security $security;
  29.         $this->environmentService $environmentService;
  30.         $this->adminRouteSecurityService $adminRouteSecurityService;
  31.     }
  32.     public static function getSubscribedEvents(): array
  33.     {
  34.         return [KernelEvents::RESPONSE => ['onKernelResponse'1]];
  35.     }
  36.     public function onKernelResponse(ResponseEvent $event): void
  37.     {
  38.         if ($this->environmentService->isApi()) {
  39.             return;
  40.         }
  41.         if ($event->getResponse()->getStatusCode() === Response::HTTP_FORBIDDEN) {
  42.             $user $this->security->getUser();
  43.             $token $this->security->getToken();
  44.             if ($user instanceof Employee || $token instanceof SwitchUserToken) {
  45.                 $event->setResponse($this->adminRouteSecurityService->redirectToAdminDashboard());
  46.                 return;
  47.             }
  48.             $url $this->router->generate('homepage');
  49.             $event->setResponse(new RedirectResponse($url));
  50.         }
  51.         if (
  52.             $event->getResponse() instanceof RedirectResponse
  53.             && $event->getRequest()->getPathInfo() === '/admin/'
  54.             && str_contains($event->getResponse()->getTargetUrl(), '/account/popuplogin')
  55.         ) {
  56.             $url $this->router->generate('admin_login');
  57.             $event->setResponse(new RedirectResponse($url));
  58.         }
  59.     }
  60. }