src/Storefront/Framework/Routing/StorefrontSubscriber.php line 250

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Storefront\Framework\Routing;
  3. use Shopware\Core\Checkout\Cart\Exception\CustomerNotLoggedInException;
  4. use Shopware\Core\Checkout\Customer\Event\CustomerLoginEvent;
  5. use Shopware\Core\Checkout\Customer\Event\CustomerLogoutEvent;
  6. use Shopware\Core\Content\Seo\HreflangLoaderInterface;
  7. use Shopware\Core\Content\Seo\HreflangLoaderParameter;
  8. use Shopware\Core\Framework\App\ActiveAppsLoader;
  9. use Shopware\Core\Framework\App\Exception\AppUrlChangeDetectedException;
  10. use Shopware\Core\Framework\App\ShopId\ShopIdProvider;
  11. use Shopware\Core\Framework\Event\BeforeSendResponseEvent;
  12. use Shopware\Core\Framework\Log\Package;
  13. use Shopware\Core\Framework\Routing\Event\SalesChannelContextResolvedEvent;
  14. use Shopware\Core\Framework\Routing\KernelListenerPriorities;
  15. use Shopware\Core\Framework\Util\Random;
  16. use Shopware\Core\PlatformRequest;
  17. use Shopware\Core\SalesChannelRequest;
  18. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  19. use Shopware\Core\System\SystemConfig\SystemConfigService;
  20. use Shopware\Storefront\Event\StorefrontRenderEvent;
  21. use Shopware\Storefront\Theme\StorefrontPluginRegistryInterface;
  22. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  23. use Symfony\Component\HttpFoundation\RedirectResponse;
  24. use Symfony\Component\HttpFoundation\RequestStack;
  25. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  26. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  27. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  28. use Symfony\Component\HttpKernel\Event\RequestEvent;
  29. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  30. use Symfony\Component\HttpKernel\KernelEvents;
  31. use Symfony\Component\Routing\RouterInterface;
  32. /**
  33.  * @internal
  34.  */
  35. #[Package('storefront')]
  36. class StorefrontSubscriber implements EventSubscriberInterface
  37. {
  38.     /**
  39.      * @internal
  40.      */
  41.     public function __construct(private readonly RequestStack $requestStack, private readonly RouterInterface $router, private readonly HreflangLoaderInterface $hreflangLoader, private readonly MaintenanceModeResolver $maintenanceModeResolver, private readonly ShopIdProvider $shopIdProvider, private readonly ActiveAppsLoader $activeAppsLoader, private readonly SystemConfigService $systemConfigService, private readonly StorefrontPluginRegistryInterface $themeRegistry)
  42.     {
  43.     }
  44.     public static function getSubscribedEvents(): array
  45.     {
  46.         return [
  47.             KernelEvents::REQUEST => [
  48.                 ['startSession'40],
  49.                 ['maintenanceResolver'],
  50.             ],
  51.             KernelEvents::EXCEPTION => [
  52.                 ['customerNotLoggedInHandler'],
  53.                 ['maintenanceResolver'],
  54.             ],
  55.             KernelEvents::CONTROLLER => [
  56.                 ['preventPageLoadingFromXmlHttpRequest'KernelListenerPriorities::KERNEL_CONTROLLER_EVENT_SCOPE_VALIDATE],
  57.             ],
  58.             CustomerLoginEvent::class => [
  59.                 'updateSessionAfterLogin',
  60.             ],
  61.             CustomerLogoutEvent::class => [
  62.                 'updateSessionAfterLogout',
  63.             ],
  64.             BeforeSendResponseEvent::class => [
  65.                 ['setCanonicalUrl'],
  66.             ],
  67.             StorefrontRenderEvent::class => [
  68.                 ['addHreflang'],
  69.                 ['addShopIdParameter'],
  70.                 ['addIconSetConfig'],
  71.             ],
  72.             SalesChannelContextResolvedEvent::class => [
  73.                 ['replaceContextToken'],
  74.             ],
  75.         ];
  76.     }
  77.     public function startSession(): void
  78.     {
  79.         $master $this->requestStack->getMainRequest();
  80.         if (!$master) {
  81.             return;
  82.         }
  83.         if (!$master->attributes->get(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  84.             return;
  85.         }
  86.         if (!$master->hasSession()) {
  87.             return;
  88.         }
  89.         $session $master->getSession();
  90.         if (!$session->isStarted()) {
  91.             $session->setName('session-');
  92.             $session->start();
  93.             $session->set('sessionId'$session->getId());
  94.         }
  95.         $salesChannelId $master->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID);
  96.         if ($salesChannelId === null) {
  97.             /** @var SalesChannelContext|null $salesChannelContext */
  98.             $salesChannelContext $master->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  99.             if ($salesChannelContext !== null) {
  100.                 $salesChannelId $salesChannelContext->getSalesChannel()->getId();
  101.             }
  102.         }
  103.         if ($this->shouldRenewToken($session$salesChannelId)) {
  104.             $token Random::getAlphanumericString(32);
  105.             $session->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  106.             $session->set(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID$salesChannelId);
  107.         }
  108.         $master->headers->set(
  109.             PlatformRequest::HEADER_CONTEXT_TOKEN,
  110.             $session->get(PlatformRequest::HEADER_CONTEXT_TOKEN)
  111.         );
  112.     }
  113.     public function updateSessionAfterLogin(CustomerLoginEvent $event): void
  114.     {
  115.         $token $event->getContextToken();
  116.         $this->updateSession($token);
  117.     }
  118.     public function updateSessionAfterLogout(): void
  119.     {
  120.         $newToken Random::getAlphanumericString(32);
  121.         $this->updateSession($newTokentrue);
  122.     }
  123.     public function updateSession(string $tokenbool $destroyOldSession false): void
  124.     {
  125.         $master $this->requestStack->getMainRequest();
  126.         if (!$master) {
  127.             return;
  128.         }
  129.         if (!$master->attributes->get(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  130.             return;
  131.         }
  132.         if (!$master->hasSession()) {
  133.             return;
  134.         }
  135.         $session $master->getSession();
  136.         $session->migrate($destroyOldSession);
  137.         $session->set('sessionId'$session->getId());
  138.         $session->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  139.         $master->headers->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  140.     }
  141.     public function customerNotLoggedInHandler(ExceptionEvent $event): void
  142.     {
  143.         if (!$event->getRequest()->attributes->has(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  144.             return;
  145.         }
  146.         if (!$event->getThrowable() instanceof CustomerNotLoggedInException) {
  147.             return;
  148.         }
  149.         $request $event->getRequest();
  150.         $parameters = [
  151.             'redirectTo' => $request->attributes->get('_route'),
  152.             'redirectParameters' => json_encode($request->attributes->get('_route_params'), \JSON_THROW_ON_ERROR),
  153.         ];
  154.         $redirectResponse = new RedirectResponse($this->router->generate('frontend.account.login.page'$parameters));
  155.         $event->setResponse($redirectResponse);
  156.     }
  157.     public function maintenanceResolver(RequestEvent $event): void
  158.     {
  159.         if ($this->maintenanceModeResolver->shouldRedirect($event->getRequest())) {
  160.             $event->setResponse(
  161.                 new RedirectResponse(
  162.                     $this->router->generate('frontend.maintenance.page'),
  163.                     RedirectResponse::HTTP_TEMPORARY_REDIRECT
  164.                 )
  165.             );
  166.         }
  167.     }
  168.     public function preventPageLoadingFromXmlHttpRequest(ControllerEvent $event): void
  169.     {
  170.         if (!$event->getRequest()->isXmlHttpRequest()) {
  171.             return;
  172.         }
  173.         /** @var list<string> $scope */
  174.         $scope $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, []);
  175.         if (!\in_array(StorefrontRouteScope::ID$scopetrue)) {
  176.             return;
  177.         }
  178.         $controller $event->getController();
  179.         // happens if Controller is a closure
  180.         if (!\is_array($controller)) {
  181.             return;
  182.         }
  183.         $isAllowed $event->getRequest()->attributes->getBoolean('XmlHttpRequest');
  184.         if ($isAllowed) {
  185.             return;
  186.         }
  187.         throw new AccessDeniedHttpException('PageController can\'t be requested via XmlHttpRequest.');
  188.     }
  189.     // used to switch session token - when the context token expired
  190.     public function replaceContextToken(SalesChannelContextResolvedEvent $event): void
  191.     {
  192.         $context $event->getSalesChannelContext();
  193.         // only update session if token expired and switched
  194.         if ($event->getUsedToken() === $context->getToken()) {
  195.             return;
  196.         }
  197.         $this->updateSession($context->getToken());
  198.     }
  199.     public function setCanonicalUrl(BeforeSendResponseEvent $event): void
  200.     {
  201.         if (!$event->getResponse()->isSuccessful()) {
  202.             return;
  203.         }
  204.         if ($canonical $event->getRequest()->attributes->get(SalesChannelRequest::ATTRIBUTE_CANONICAL_LINK)) {
  205.             $canonical sprintf('<%s>; rel="canonical"'$canonical);
  206.             $event->getResponse()->headers->set('Link'$canonical);
  207.         }
  208.     }
  209.     public function addHreflang(StorefrontRenderEvent $event): void
  210.     {
  211.         $request $event->getRequest();
  212.         $route $request->attributes->get('_route');
  213.         if ($route === null) {
  214.             return;
  215.         }
  216.         $routeParams $request->attributes->get('_route_params', []);
  217.         $salesChannelContext $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  218.         $parameter = new HreflangLoaderParameter($route$routeParams$salesChannelContext);
  219.         $event->setParameter('hrefLang'$this->hreflangLoader->load($parameter));
  220.     }
  221.     public function addShopIdParameter(StorefrontRenderEvent $event): void
  222.     {
  223.         if (!$this->activeAppsLoader->getActiveApps()) {
  224.             return;
  225.         }
  226.         try {
  227.             $shopId $this->shopIdProvider->getShopId();
  228.         } catch (AppUrlChangeDetectedException) {
  229.             return;
  230.         }
  231.         $event->setParameter('appShopId'$shopId);
  232.     }
  233.     public function addIconSetConfig(StorefrontRenderEvent $event): void
  234.     {
  235.         $request $event->getRequest();
  236.         // get name if theme is not inherited
  237.         $theme $request->attributes->get(SalesChannelRequest::ATTRIBUTE_THEME_NAME);
  238.         if (!$theme) {
  239.             // get theme name from base theme because for inherited themes the name is always null
  240.             $theme $request->attributes->get(SalesChannelRequest::ATTRIBUTE_THEME_BASE_NAME);
  241.         }
  242.         if (!$theme) {
  243.             return;
  244.         }
  245.         $themeConfig $this->themeRegistry->getConfigurations()->getByTechnicalName($theme);
  246.         if (!$themeConfig) {
  247.             return;
  248.         }
  249.         $iconConfig = [];
  250.         foreach ($themeConfig->getIconSets() as $pack => $path) {
  251.             $iconConfig[$pack] = [
  252.                 'path' => $path,
  253.                 'namespace' => $theme,
  254.             ];
  255.         }
  256.         $event->setParameter('themeIconConfig'$iconConfig);
  257.     }
  258.     private function shouldRenewToken(SessionInterface $session, ?string $salesChannelId null): bool
  259.     {
  260.         if (!$session->has(PlatformRequest::HEADER_CONTEXT_TOKEN) || $salesChannelId === null) {
  261.             return true;
  262.         }
  263.         if ($this->systemConfigService->get('core.systemWideLoginRegistration.isCustomerBoundToSalesChannel')) {
  264.             return $session->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID) !== $salesChannelId;
  265.         }
  266.         return false;
  267.     }
  268. }