<?php
namespace MedBrief\MSR\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Prevents background API requests from becoming the post-login redirect target.
*
* Symfony stores `_security.main.target_path` for any safe, non-XHR request that
* hits an authentication entry point. The React island's polling fetches qualify,
* so an expired session leaves the raw JSON endpoint as the stored target path and
* the user is dropped onto it after logging back in.
*/
class ApiTargetPathSubscriber implements EventSubscriberInterface
{
private const SESSION_KEY = '_security.main.target_path';
private const API_PREFIXES = [
'/msr/match/admin/thread-queue',
'/msr/match/admin/thread-history',
'/msr/users/me/activity',
'/msr/match_letter',
];
public static function getSubscribedEvents(): array
{
// Priority -10: runs after Symfony's ExceptionListener has written the value.
return [KernelEvents::RESPONSE => ['onKernelResponse', -10]];
}
public function onKernelResponse(ResponseEvent $event): void
{
$request = $event->getRequest();
if (!$request->hasSession() || !$request->getSession()->isStarted()) {
return;
}
$session = $request->getSession();
$targetPath = $session->get(self::SESSION_KEY);
if (!is_string($targetPath)) {
return;
}
$path = parse_url($targetPath, PHP_URL_PATH) ?: $targetPath;
foreach (self::API_PREFIXES as $prefix) {
if (str_starts_with($path, $prefix)) {
$session->remove(self::SESSION_KEY);
return;
}
}
}
}