<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Service\ParameterService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
final class PlatformModeAccessSubscriber implements EventSubscriberInterface
{
/**
* @param list<string> $protectedPathPrefixes
*/
public function __construct(
private readonly ParameterService $parameterService,
private readonly AuthorizationCheckerInterface $authorizationChecker,
private readonly UrlGeneratorInterface $urlGenerator,
private readonly array $protectedPathPrefixes,
) {}
public static function getSubscribedEvents(): array
{
// Run after routing and firewall authentication so the route and user token are available.
return [KernelEvents::REQUEST => ['onKernelRequest', 0]];
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
if (
!$this->matchesProtectedPath($request->getPathInfo())
|| !$this->parameterService->isB2BMode()
) {
return;
}
// B2B product routes require a fully authenticated session, including completed 2FA.
if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
return;
}
$loginUrl = $this->urlGenerator->generate('app_login', ['type' => 'btob']);
$accept = $request->headers->get('Accept', '');
if ($request->isXmlHttpRequest() || str_contains($accept, 'application/json')) {
$event->setResponse(new JsonResponse([
'error' => 'Authentication required',
'loginUrl' => $loginUrl,
], JsonResponse::HTTP_UNAUTHORIZED));
return;
}
$event->setResponse(new RedirectResponse($loginUrl));
}
private function matchesProtectedPath(string $path): bool
{
foreach ($this->protectedPathPrefixes as $prefix) {
$prefix = '/' . trim($prefix, '/');
if ($path === $prefix || str_starts_with($path, $prefix . '/')) {
return true;
}
}
return false;
}
}