<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\System\Employee;
use App\Service\EnvironmentService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Security;
class NotAuthorizedResponseSubscriber implements EventSubscriberInterface
{
private RouterInterface $router;
private Security $security;
private EnvironmentService $environmentService;
private UrlGeneratorInterface $urlGenerator;
public function __construct(
RouterInterface $router,
Security $security,
EnvironmentService $environmentService,
UrlGeneratorInterface $urlGenerator
) {
$this->router = $router;
$this->security = $security;
$this->environmentService = $environmentService;
$this->urlGenerator = $urlGenerator;
}
public static function getSubscribedEvents(): array
{
return [KernelEvents::RESPONSE => ['onKernelResponse', 1]];
}
public function onKernelResponse(ResponseEvent $event): void
{
if ($this->environmentService->isApi()) {
return;
}
if ($event->getResponse()->getStatusCode() === Response::HTTP_FORBIDDEN) {
$user = $this->security->getUser();
$token = $this->security->getToken();
if ($user instanceof Employee || $token instanceof SwitchUserToken) {
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('admin_dashboard_index')));
return;
}
$url = $this->router->generate('homepage');
$event->setResponse(new RedirectResponse($url));
}
}
}