vendor/symfony/http-kernel/EventListener/AbstractSessionListener.php line 211

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\HttpKernel\EventListener;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpFoundation\Cookie;
  14. use Symfony\Component\HttpFoundation\Session\Session;
  15. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  16. use Symfony\Component\HttpFoundation\Session\SessionUtils;
  17. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  18. use Symfony\Component\HttpKernel\Event\RequestEvent;
  19. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  20. use Symfony\Component\HttpKernel\Exception\UnexpectedSessionUsageException;
  21. use Symfony\Component\HttpKernel\KernelEvents;
  22. use Symfony\Contracts\Service\ResetInterface;
  23. /**
  24.  * Sets the session onto the request on the "kernel.request" event and saves
  25.  * it on the "kernel.response" event.
  26.  *
  27.  * In addition, if the session has been started it overrides the Cache-Control
  28.  * header in such a way that all caching is disabled in that case.
  29.  * If you have a scenario where caching responses with session information in
  30.  * them makes sense, you can disable this behaviour by setting the header
  31.  * AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER on the response.
  32.  *
  33.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  34.  * @author Tobias Schultze <http://tobion.de>
  35.  *
  36.  * @internal
  37.  */
  38. abstract class AbstractSessionListener implements EventSubscriberInterfaceResetInterface
  39. {
  40.     public const NO_AUTO_CACHE_CONTROL_HEADER 'Symfony-Session-NoAutoCacheControl';
  41.     protected $container;
  42.     private $sessionUsageStack = [];
  43.     private $debug;
  44.     /**
  45.      * @var array<string, mixed>
  46.      */
  47.     private $sessionOptions;
  48.     public function __construct(ContainerInterface $container nullbool $debug false, array $sessionOptions = [])
  49.     {
  50.         $this->container $container;
  51.         $this->debug $debug;
  52.         $this->sessionOptions $sessionOptions;
  53.     }
  54.     public function onKernelRequest(RequestEvent $event)
  55.     {
  56.         if (!$event->isMainRequest()) {
  57.             return;
  58.         }
  59.         $request $event->getRequest();
  60.         if (!$request->hasSession()) {
  61.             // This variable prevents calling `$this->getSession()` twice in case the Request (and the below factory) is cloned
  62.             $sess null;
  63.             $request->setSessionFactory(function () use (&$sess$request) {
  64.                 if (!$sess) {
  65.                     $sess $this->getSession();
  66.                 }
  67.                 /*
  68.                  * For supporting sessions in php runtime with runners like roadrunner or swoole the session
  69.                  * cookie need read from the cookie bag and set on the session storage.
  70.                  */
  71.                 if ($sess && !$sess->isStarted()) {
  72.                     $sessionId $request->cookies->get($sess->getName(), '');
  73.                     $sess->setId($sessionId);
  74.                 }
  75.                 return $sess;
  76.             });
  77.         }
  78.         $session $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : null;
  79.         $this->sessionUsageStack[] = $session instanceof Session $session->getUsageIndex() : 0;
  80.     }
  81.     public function onKernelResponse(ResponseEvent $event)
  82.     {
  83.         if (!$event->isMainRequest()) {
  84.             return;
  85.         }
  86.         $response $event->getResponse();
  87.         $autoCacheControl = !$response->headers->has(self::NO_AUTO_CACHE_CONTROL_HEADER);
  88.         // Always remove the internal header if present
  89.         $response->headers->remove(self::NO_AUTO_CACHE_CONTROL_HEADER);
  90.         if (!$session $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : $event->getRequest()->getSession()) {
  91.             return;
  92.         }
  93.         if ($session->isStarted()) {
  94.             /*
  95.              * Saves the session, in case it is still open, before sending the response/headers.
  96.              *
  97.              * This ensures several things in case the developer did not save the session explicitly:
  98.              *
  99.              *  * If a session save handler without locking is used, it ensures the data is available
  100.              *    on the next request, e.g. after a redirect. PHPs auto-save at script end via
  101.              *    session_register_shutdown is executed after fastcgi_finish_request. So in this case
  102.              *    the data could be missing the next request because it might not be saved the moment
  103.              *    the new request is processed.
  104.              *  * A locking save handler (e.g. the native 'files') circumvents concurrency problems like
  105.              *    the one above. But by saving the session before long-running things in the terminate event,
  106.              *    we ensure the session is not blocked longer than needed.
  107.              *  * When regenerating the session ID no locking is involved in PHPs session design. See
  108.              *    https://bugs.php.net/61470 for a discussion. So in this case, the session must
  109.              *    be saved anyway before sending the headers with the new session ID. Otherwise session
  110.              *    data could get lost again for concurrent requests with the new ID. One result could be
  111.              *    that you get logged out after just logging in.
  112.              *
  113.              * This listener should be executed as one of the last listeners, so that previous listeners
  114.              * can still operate on the open session. This prevents the overhead of restarting it.
  115.              * Listeners after closing the session can still work with the session as usual because
  116.              * Symfonys session implementation starts the session on demand. So writing to it after
  117.              * it is saved will just restart it.
  118.              */
  119.             $session->save();
  120.             /*
  121.              * For supporting sessions in php runtime with runners like roadrunner or swoole the session
  122.              * cookie need to be written on the response object and should not be written by PHP itself.
  123.              */
  124.             $sessionName $session->getName();
  125.             $sessionId $session->getId();
  126.             $sessionCookiePath $this->sessionOptions['cookie_path'] ?? '/';
  127.             $sessionCookieDomain $this->sessionOptions['cookie_domain'] ?? null;
  128.             $sessionCookieSecure $this->sessionOptions['cookie_secure'] ?? false;
  129.             $sessionCookieHttpOnly $this->sessionOptions['cookie_httponly'] ?? true;
  130.             $sessionCookieSameSite $this->sessionOptions['cookie_samesite'] ?? Cookie::SAMESITE_LAX;
  131.             SessionUtils::popSessionCookie($sessionName$sessionId);
  132.             $request $event->getRequest();
  133.             $requestSessionCookieId $request->cookies->get($sessionName);
  134.             if ($requestSessionCookieId && $session->isEmpty()) {
  135.                 $response->headers->clearCookie(
  136.                     $sessionName,
  137.                     $sessionCookiePath,
  138.                     $sessionCookieDomain,
  139.                     $sessionCookieSecure,
  140.                     $sessionCookieHttpOnly,
  141.                     $sessionCookieSameSite
  142.                 );
  143.             } elseif ($sessionId !== $requestSessionCookieId) {
  144.                 $expire 0;
  145.                 $lifetime $this->sessionOptions['cookie_lifetime'] ?? null;
  146.                 if ($lifetime) {
  147.                     $expire time() + $lifetime;
  148.                 }
  149.                 $response->headers->setCookie(
  150.                     Cookie::create(
  151.                         $sessionName,
  152.                         $sessionId,
  153.                         $expire,
  154.                         $sessionCookiePath,
  155.                         $sessionCookieDomain,
  156.                         $sessionCookieSecure,
  157.                         $sessionCookieHttpOnly,
  158.                         false,
  159.                         $sessionCookieSameSite
  160.                     )
  161.                 );
  162.             }
  163.         }
  164.         if ($session instanceof Session $session->getUsageIndex() === end($this->sessionUsageStack) : !$session->isStarted()) {
  165.             return;
  166.         }
  167.         if ($autoCacheControl) {
  168.             $response
  169.                 ->setExpires(new \DateTime())
  170.                 ->setPrivate()
  171.                 ->setMaxAge(0)
  172.                 ->headers->addCacheControlDirective('must-revalidate');
  173.         }
  174.         if (!$event->getRequest()->attributes->get('_stateless'false)) {
  175.             return;
  176.         }
  177.         if ($this->debug) {
  178.             throw new UnexpectedSessionUsageException('Session was used while the request was declared stateless.');
  179.         }
  180.         if ($this->container->has('logger')) {
  181.             $this->container->get('logger')->warning('Session was used while the request was declared stateless.');
  182.         }
  183.     }
  184.     public function onFinishRequest(FinishRequestEvent $event)
  185.     {
  186.         if ($event->isMainRequest()) {
  187.             array_pop($this->sessionUsageStack);
  188.         }
  189.     }
  190.     public function onSessionUsage(): void
  191.     {
  192.         if (!$this->debug) {
  193.             return;
  194.         }
  195.         if ($this->container && $this->container->has('session_collector')) {
  196.             $this->container->get('session_collector')();
  197.         }
  198.         if (!$requestStack $this->container && $this->container->has('request_stack') ? $this->container->get('request_stack') : null) {
  199.             return;
  200.         }
  201.         $stateless false;
  202.         $clonedRequestStack = clone $requestStack;
  203.         while (null !== ($request $clonedRequestStack->pop()) && !$stateless) {
  204.             $stateless $request->attributes->get('_stateless');
  205.         }
  206.         if (!$stateless) {
  207.             return;
  208.         }
  209.         if (!$session $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : $requestStack->getCurrentRequest()->getSession()) {
  210.             return;
  211.         }
  212.         if ($session->isStarted()) {
  213.             $session->save();
  214.         }
  215.         throw new UnexpectedSessionUsageException('Session was used while the request was declared stateless.');
  216.     }
  217.     public static function getSubscribedEvents(): array
  218.     {
  219.         return [
  220.             KernelEvents::REQUEST => ['onKernelRequest'128],
  221.             // low priority to come after regular response listeners, but higher than StreamedResponseListener
  222.             KernelEvents::RESPONSE => ['onKernelResponse', -1000],
  223.             KernelEvents::FINISH_REQUEST => ['onFinishRequest'],
  224.         ];
  225.     }
  226.     public function reset(): void
  227.     {
  228.         if (\PHP_SESSION_ACTIVE === session_status()) {
  229.             session_abort();
  230.         }
  231.         session_unset();
  232.         $_SESSION = [];
  233.         if (!headers_sent()) { // session id can only be reset when no headers were so we check for headers_sent first
  234.             session_id('');
  235.         }
  236.     }
  237.     /**
  238.      * Gets the session object.
  239.      *
  240.      * @return SessionInterface|null
  241.      */
  242.     abstract protected function getSession();
  243. }