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\EnvironmentService;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  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 UrlGeneratorInterface $urlGenerator;
  21. public function __construct(
  22. RouterInterface $router,
  23. Security $security,
  24. EnvironmentService $environmentService,
  25. UrlGeneratorInterface $urlGenerator
  26. ) {
  27. $this->router = $router;
  28. $this->security = $security;
  29. $this->environmentService = $environmentService;
  30. $this->urlGenerator = $urlGenerator;
  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(new RedirectResponse($this->urlGenerator->generate('admin_dashboard_index')));
  46. return;
  47. }
  48. $url = $this->router->generate('homepage');
  49. $event->setResponse(new RedirectResponse($url));
  50. }
  51. }
  52. }