src/Component/Event/AjaxAuthenticationListener.php line 29

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\Component\Event;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  5. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  6. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  7. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  8. /**
  9. * This Listener ensures that a Forbidden response is returned on Ajax Responses
  10. * when there is an Authentication Exception. This class is courtesy of:
  11. * https://gist.github.com/xanf/1015146
  12. *
  13. * @todo This class makes no distinction between a user not being logged in VS
  14. * being logged in and actually not having access to the URL. This distinction
  15. * should probably be made so that we don't reload the page on the JS side when
  16. * we should actually just be returning a forbidden response?
  17. *
  18. */
  19. class AjaxAuthenticationListener
  20. {
  21. /**
  22. * Handles security related exceptions.
  23. *
  24. * @param ExceptionEvent $event An GetResponseForExceptionEvent instance
  25. */
  26. public function onCoreException(ExceptionEvent $event): void
  27. {
  28. $exception = $event->getThrowable();
  29. $request = $event->getRequest();
  30. if ($request->isXmlHttpRequest() && ($exception instanceof AuthenticationException || $exception instanceof AccessDeniedException)) {
  31. $event->setResponse(new Response('', 403));
  32. }
  33. }
  34. }