Skip to content

[2.3][Session] Give greater control over how and when session starts #7855

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ CHANGELOG
* added support for default templates per render tag
* added FormHelper::form(), FormHelper::start() and FormHelper::end()
* deprecated FormHelper::enctype() in favor of FormHelper::start()
* Reintroduce `auto_start` session config flag to instruct the `SessionListener` to manually start session
* Added session config option `on_demand_mode` to control session start on demand.

2.2.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,16 @@ private function addSessionSection(ArrayNodeDefinition $rootNode)
->info('session configuration')
->canBeUnset()
->children()
->booleanNode('auto_start')
->defaultFalse()
->info('Flag for SessionListener to start session')
->end()
->enumNode('on_demand_mode')
->values(array('off', 'on', 'off_lax'))
->defaultValue('on')
->info('Start session on demand: off, on, or off_lax')
->end()
->scalarNode('mock_name')->defaultValue('MOCKSESSID')->end()
->scalarNode('storage_id')->defaultValue('session.storage.native')->end()
->scalarNode('handler_id')->defaultValue('session.handler.native_file')->end()
->scalarNode('name')->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Config\Resource\DirectoryResource;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Config\FileLocator;

Expand Down Expand Up @@ -314,6 +315,14 @@ private function registerSessionConfiguration(array $config, ContainerBuilder $c

$container->setParameter('session.storage.options', $options);

// this controls the SessionListener to start session
$container->setParameter('session.auto_start', $config['auto_start']);

// this controls the session start on demand feature
$container->setParameter('session.storage.on_demand_mode', $config['on_demand_mode']);

$container->setParameter('session.storage.mock_name', $config['mock_name']);

// session handler (the internal callback registered with PHP session management)
if (null == $config['handler_id']) {
// Set the handler class to be null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@ class SessionListener implements EventSubscriberInterface
* @var ContainerInterface
*/
private $container;
private $autoStart;

public function __construct(ContainerInterface $container)
public function __construct(ContainerInterface $container, $autoStart = false)
{
$this->container = $container;
$this->autoStart = $autoStart;
}

public function onKernelRequest(GetResponseEvent $event)
Expand All @@ -46,7 +48,11 @@ public function onKernelRequest(GetResponseEvent $event)
return;
}

$request->setSession($this->container->get('session'));
$request->setSession($session = $this->container->get('session'));

if ($this->autoStart || $request->hasPreviousSession()) {
$session->start();
}
}

public static function getSubscribedEvents()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@
</xsd:complexType>

<xsd:complexType name="session">
<xsd:attribute name="auto-start" type="xsd:boolean" />
<xsd:attribute name="on-demand-mode" type="xsd:string" />
<xsd:attribute name="mock-name" type="xsd:string" />
<xsd:attribute name="storage-id" type="xsd:string" />
<xsd:attribute name="handler-id" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<parameter key="session.class">Symfony\Component\HttpFoundation\Session\Session</parameter>
<parameter key="session.flashbag.class">Symfony\Component\HttpFoundation\Session\Flash\FlashBag</parameter>
<parameter key="session.attribute_bag.class">Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag</parameter>
<parameter key="session.metadata_bag.class">Symfony\Component\HttpFoundation\Session\Storage\MetadataBag</parameter>
<parameter key="session.storage.native.class">Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage</parameter>
<parameter key="session.storage.php_bridge.class">Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage</parameter>
<parameter key="session.storage.mock_file.class">Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage</parameter>
Expand All @@ -25,18 +26,24 @@
<service id="session.storage.native" class="%session.storage.native.class%">
<argument>%session.storage.options%</argument>
<argument type="service" id="session.handler" />
<argument type="service" id="session.metadata_bag" />
<argument>%session.storage.on_demand_mode%</argument>
</service>

<service id="session.storage.php_bridge" class="%session.storage.php_bridge.class%">
<argument type="service" id="session.handler" />
</service>

<service id="session.flash_bag" class="%session.flashbag.class%" public="false" />
<service id="session.metadata_bag" class="%session.metadata_bag.class%" public="false" />

<service id="session.attribute_bag" class="%session.attribute_bag.class%" public="false" />

<service id="session.storage.mock_file" class="%session.storage.mock_file.class%" public="false">
<argument>%kernel.cache_dir%/sessions</argument>
<argument>%session.storage.mock_name%</argument>
<argument type="service" id="session.metadata_bag" />
<argument>%session.storage.on_demand_mode%</argument>
</service>

<service id="session.handler.native_file" class="%session.handler.native_file.class%" public="false">
Expand All @@ -46,6 +53,7 @@
<service id="session_listener" class="%session_listener.class%">
<tag name="kernel.event_subscriber" />
<argument type="service" id="service_container" />
<argument>%session.auto_start%</argument>
</service>

<!-- for BC -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
'session' => array(
'storage_id' => 'session.storage.native',
'handler_id' => 'session.handler.native_file',
'auto_start' => true,
'on_demand_mode' => 'on',
'name' => '_SYMFONY',
'cookie_lifetime' => 86400,
'cookie_path' => '/',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<framework:esi enabled="true" />
<framework:profiler only-exceptions="true" enabled="false" />
<framework:router resource="%kernel.root_dir%/config/routing.xml" type="xml" />
<framework:session gc-maxlifetime="90000" gc-probability="1" gc-divisor="108" storage-id="session.storage.native" handler-id="session.handler.native_file" name="_SYMFONY" cookie-lifetime="86400" cookie-path="/" cookie-domain="example.com" cookie-secure="true" cookie-httponly="true" save-path="/path/to/sessions" />
<framework:session gc-maxlifetime="90000" gc-probability="1" gc-divisor="108" storage-id="session.storage.native" handler-id="session.handler.native_file" name="_SYMFONY" cookie-lifetime="86400" cookie-path="/" cookie-domain="example.com" cookie-secure="true" cookie-httponly="true" save-path="/path/to/sessions" auto-start="true" on-demand-mode="on" />
<framework:templating assets-version="SomeVersionScheme" cache="/path/to/cache" >
<framework:loader>loader.foo</framework:loader>
<framework:loader>loader.bar</framework:loader>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ framework:
session:
storage_id: session.storage.native
handler_id: session.handler.native_file
auto_start: true
on_demand_mode: on
name: _SYMFONY
cookie_lifetime: 86400
cookie_path: /
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ public function testSession()
$this->assertEquals('session.storage.native', (string) $container->getAlias('session.storage'));
$this->assertEquals('session.handler.native_file', (string) $container->getAlias('session.handler'));

$this->assertTrue($container->getParameter('session.auto_start'));
$this->assertEquals($container->getParameter('session.storage.on_demand_mode'), 'on');

$options = $container->getParameter('session.storage.options');
$this->assertEquals('_SYMFONY', $options['name']);
$this->assertEquals(86400, $options['cookie_lifetime']);
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpFoundation/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* added support for ranges of IPs in trusted proxies
* `UploadedFile::isValid` now returns false if the file was not uploaded via HTTP (in a non-test mode)
* added control for session start on demand.

2.2.0
-----
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/HttpFoundation/Session/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* Constructor.
*
* @param SessionStorageInterface $storage A SessionStorageInterface instance.
* @param SessionStorageInterface $storage A SessionStorageInterface instance
* @param AttributeBagInterface $attributes An AttributeBagInterface instance, (defaults null for default AttributeBag)
* @param FlashBagInterface $flashes A FlashBagInterface instance (defaults null for default FlashBag)
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function getStorageKey();
/**
* Clears out data from bag.
*
* @return mixed Whatever data was contained.
* @return mixed Whatever data was contained
*/
public function clear();
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ interface SessionInterface
/**
* Starts the session storage.
*
* @return Boolean True if session started.
* @return Boolean True if session started
*
* @throws \RuntimeException If session fails to start.
* @throws \RuntimeException If session fails to start
*
* @api
*/
Expand All @@ -34,7 +34,7 @@ public function start();
/**
* Returns the session ID.
*
* @return string The session ID.
* @return string The session ID
*
* @api
*/
Expand All @@ -52,7 +52,7 @@ public function setId($id);
/**
* Returns the session name.
*
* @return mixed The session name.
* @return mixed The session name
*
* @api
*/
Expand All @@ -76,9 +76,9 @@ public function setName($name);
* @param integer $lifetime Sets the cookie lifetime for the session cookie. A null value
* will leave the system settings unchanged, 0 sets the cookie
* to expire with browser session. Time is in seconds, and is
* not a Unix timestamp.
* not a Unix timestamp
*
* @return Boolean True if session invalidated, false if error.
* @return Boolean True if session invalidated, false if error
*
* @api
*/
Expand All @@ -92,9 +92,9 @@ public function invalidate($lifetime = null);
* @param integer $lifetime Sets the cookie lifetime for the session cookie. A null value
* will leave the system settings unchanged, 0 sets the cookie
* to expire with browser session. Time is in seconds, and is
* not a Unix timestamp.
* not a Unix timestamp
*
* @return Boolean True if session migrated, false if error.
* @return Boolean True if session migrated, false if error
*
* @api
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class MemcacheSessionHandler implements \SessionHandlerInterface
private $ttl;

/**
* @var string Key prefix for shared environments.
* @var string Key prefix for shared environments
*/
private $prefix;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class MemcachedSessionHandler implements \SessionHandlerInterface
private $ttl;

/**
* @var string Key prefix for shared environments.
* @var string Key prefix for shared environments
*/
private $prefix;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ class MongoDbSessionHandler implements \SessionHandlerInterface
public function __construct($mongo, array $options)
{
if (!($mongo instanceof \MongoClient || $mongo instanceof \Mongo)) {
throw new \InvalidArgumentException('MongoClient or Mongo instance required');
throw new \InvalidArgumentException('MongoClient or Mongo instance required.');
}

if (!isset($options['database']) || !isset($options['collection'])) {
throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler');
throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler.');
}

$this->mongo = $mongo;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ class NativeFileSessionHandler extends NativeSessionHandler
* Constructor.
*
* @param string $savePath Path of directory to save session files.
* Default null will leave setting as defined by PHP.
* Default null will leave setting as defined by PHP
* '/path', 'N;/path', or 'N;octal-mode;/path
*
* @see http://php.net/session.configuration.php#ini.session.save-path for further details.
* @see http://php.net/session.configuration.php#ini.session.save-path for further details
*
* @throws \InvalidArgumentException On invalid $savePath
*/
Expand All @@ -41,7 +41,7 @@ public function __construct($savePath = null)

if ($count = substr_count($savePath, ';')) {
if ($count > 2) {
throw new \InvalidArgumentException(sprintf('Invalid argument $savePath \'%s\'', $savePath));
throw new \InvalidArgumentException(sprintf('Invalid argument $savePath \'%s\'.', $savePath));
}

// characters after last ';' are the path
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@
class PdoSessionHandler implements \SessionHandlerInterface
{
/**
* @var \PDO PDO instance.
* @var \PDO PDO instance
*/
private $pdo;

/**
* @var array Database options.
* @var array Database options
*/
private $dbOptions;

Expand Down Expand Up @@ -90,7 +90,7 @@ public function destroy($id)
$stmt->bindParam(':id', $id, \PDO::PARAM_STR);
$stmt->execute();
} catch (\PDOException $e) {
throw new \RuntimeException(sprintf('PDOException was thrown when trying to manipulate session data: %s', $e->getMessage()), 0, $e);
throw new \RuntimeException(sprintf('PDOException was thrown when trying to manipulate session data: %s.', $e->getMessage()), 0, $e);
}

return true;
Expand All @@ -113,7 +113,7 @@ public function gc($lifetime)
$stmt->bindValue(':time', time() - $lifetime, \PDO::PARAM_INT);
$stmt->execute();
} catch (\PDOException $e) {
throw new \RuntimeException(sprintf('PDOException was thrown when trying to manipulate session data: %s', $e->getMessage()), 0, $e);
throw new \RuntimeException(sprintf('PDOException was thrown when trying to manipulate session data: %s.', $e->getMessage()), 0, $e);
}

return true;
Expand Down Expand Up @@ -149,7 +149,7 @@ public function read($id)

return '';
} catch (\PDOException $e) {
throw new \RuntimeException(sprintf('PDOException was thrown when trying to read the session data: %s', $e->getMessage()), 0, $e);
throw new \RuntimeException(sprintf('PDOException was thrown when trying to read the session data: %s.', $e->getMessage()), 0, $e);
}
}

Expand Down Expand Up @@ -204,7 +204,7 @@ public function write($id, $data)
}
}
} catch (\PDOException $e) {
throw new \RuntimeException(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
throw new \RuntimeException(sprintf('PDOException was thrown when trying to write the session data: %s.', $e->getMessage()), 0, $e);
}

return true;
Expand All @@ -216,7 +216,7 @@ public function write($id, $data)
* @param string $id
* @param string $data
*
* @return boolean True.
* @return boolean True
*/
private function createNewSession($id, $data = '')
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class MetadataBag implements SessionBagInterface
/**
* Constructor.
*
* @param string $storageKey The key used to store bag in the session.
* @param string $storageKey The key used to store bag in the session
*/
public function __construct($storageKey = '_sf2_meta')
{
Expand Down Expand Up @@ -90,7 +90,7 @@ public function getLifetime()
* @param integer $lifetime Sets the cookie lifetime for the session cookie. A null value
* will leave the system settings unchanged, 0 sets the cookie
* to expire with browser session. Time is in seconds, and is
* not a Unix timestamp.
* not a Unix timestamp
*/
public function stampNew($lifetime = null)
{
Expand Down
Loading