src/EventSubscriber/ApiTargetPathSubscriber.php line 43

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. /**
  7. * Prevents background API requests from becoming the post-login redirect target.
  8. *
  9. * Symfony stores `_security.main.target_path` for any safe, non-XHR request that
  10. * hits an authentication entry point. The React island's polling fetches qualify,
  11. * so an expired session leaves the raw JSON endpoint as the stored target path and
  12. * the user is dropped onto it after logging back in.
  13. */
  14. class ApiTargetPathSubscriber implements EventSubscriberInterface
  15. {
  16. private const SESSION_KEY = '_security.main.target_path';
  17. private const API_PREFIXES = [
  18. '/msr/match/admin/thread-queue',
  19. '/msr/match/admin/thread-history',
  20. '/msr/users/me/activity',
  21. '/msr/match_letter',
  22. ];
  23. public static function getSubscribedEvents(): array
  24. {
  25. // Priority -10: runs after Symfony's ExceptionListener has written the value.
  26. return [KernelEvents::RESPONSE => ['onKernelResponse', -10]];
  27. }
  28. public function onKernelResponse(ResponseEvent $event): void
  29. {
  30. $request = $event->getRequest();
  31. if (!$request->hasSession() || !$request->getSession()->isStarted()) {
  32. return;
  33. }
  34. $session = $request->getSession();
  35. $targetPath = $session->get(self::SESSION_KEY);
  36. if (!is_string($targetPath)) {
  37. return;
  38. }
  39. $path = parse_url($targetPath, PHP_URL_PATH) ?: $targetPath;
  40. foreach (self::API_PREFIXES as $prefix) {
  41. if (str_starts_with($path, $prefix)) {
  42. $session->remove(self::SESSION_KEY);
  43. return;
  44. }
  45. }
  46. }
  47. }