Commit ba751b43 by Taylor Otwell

restructured session handling.

parent f68a918d
...@@ -40,7 +40,7 @@ return array( ...@@ -40,7 +40,7 @@ return array(
| |
*/ */
'key' => '', 'key' => 'some_secret_key',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
......
...@@ -109,12 +109,6 @@ return array( ...@@ -109,12 +109,6 @@ return array(
| |
*/ */
'laravel.session.id' => array('singleton' => true, 'resolver' => function($c)
{
return Cookie::get('laravel_session');
}),
'laravel.session.manager' => array('singleton' => true, 'resolver' => function($c) 'laravel.session.manager' => array('singleton' => true, 'resolver' => function($c)
{ {
$driver = $c->core('session.'.Config::get('session.driver')); $driver = $c->core('session.'.Config::get('session.driver'));
......
...@@ -26,9 +26,11 @@ date_default_timezone_set(Config::$items['application']['timezone']); ...@@ -26,9 +26,11 @@ date_default_timezone_set(Config::$items['application']['timezone']);
*/ */
if (Config::$items['session']['driver'] !== '') if (Config::$items['session']['driver'] !== '')
{ {
$session = IoC::container()->core('session.manager'); $driver = IoC::container()->core('session.'.Config::$items['session']['driver']);
Session\Manager::$payload = $session->payload(Config::$items['session']); $transporter = IoC::container()->core('session.transporter');
Session\Manager::start($driver, $transporter);
} }
/** /**
...@@ -107,11 +109,11 @@ $response->content = $response->render(); ...@@ -107,11 +109,11 @@ $response->content = $response->render();
* to the session so it will be available for the next request * to the session so it will be available for the next request
* via the Input::old method. * via the Input::old method.
*/ */
if (isset($session)) if (Config::$items['session']['driver'] !== '')
{ {
$flash = array(Input::old_input => Input::get()); $flash = array(Input::old_input => Input::get());
$session->close(Session\Manager::$payload, Config::$items['session'], $flash); Session\Manager::close($driver, $transporter, $flash);
} }
/** /**
......
...@@ -62,7 +62,7 @@ class Auth { ...@@ -62,7 +62,7 @@ class Auth {
{ {
if ( ! is_null(static::$user)) return static::$user; if ( ! is_null(static::$user)) return static::$user;
static::$user = call_user_func(Config::get('auth.user'), Session::$payload->get(Auth::user_key)); static::$user = call_user_func(Config::get('auth.user'), Session::get(Auth::user_key));
if (is_null(static::$user) and ! is_null($cookie = Cookie::get(Auth::remember_key))) if (is_null(static::$user) and ! is_null($cookie = Cookie::get(Auth::remember_key)))
{ {
...@@ -142,7 +142,7 @@ class Auth { ...@@ -142,7 +142,7 @@ class Auth {
if ($remember) static::remember($user->id, $user->{Config::get('auth.username')}); if ($remember) static::remember($user->id, $user->{Config::get('auth.username')});
Session::$payload->put(Auth::user_key, $user->id); Session::put(Auth::user_key, $user->id);
} }
/** /**
...@@ -183,7 +183,7 @@ class Auth { ...@@ -183,7 +183,7 @@ class Auth {
Cookie::forget(Auth::remember_key); Cookie::forget(Auth::remember_key);
Session::$payload->forget(Auth::user_key); Session::forget(Auth::user_key);
} }
} }
\ No newline at end of file
...@@ -8,135 +8,271 @@ use Laravel\Session\Transporters\Transporter; ...@@ -8,135 +8,271 @@ use Laravel\Session\Transporters\Transporter;
class Manager { class Manager {
/** /**
* The session driver instance. * The current session payload.
*
* @var Driver
*/
private $driver;
/**
* The session identifier transporter instance.
* *
* @var Transporter * @var array
*/ */
private $transporter; protected static $session = array();
/** /**
* Indicates if the session exists in persistent storage. * Indicates if the session exists in persistent storage.
* *
* @var bool * @var bool
*/ */
private $exists = true; protected static $exists = true;
/**
* The current session payload.
*
* @var Payload
*/
public static $payload;
/** /**
* Create a new session manager instance. * Indicates if the session ID has been regenerated.
* *
* @param Driver $driver * @var bool
* @param Transporter $transporter
* @return void
*/ */
public function __construct(Driver $driver, Transporter $transporter) protected static $regenerated = false;
{
$this->driver = $driver;
$this->transporter = $transporter;
}
/** /**
* Get the session payload for the request. * Start the session handling for the current request.
* *
* @param array $config * @param Drivers\Driver $driver
* @param Transporters\Transporter $transporter
* @return Payload * @return Payload
*/ */
public function payload($config) public static function start(Driver $driver, Transporter $transporter)
{ {
$session = $this->driver->load($this->transporter->get($config)); $config = Config::$items['session'];
static::$session = $driver->load($transporter->get($config));
// If the session is expired, a new session will be generated and all of // If the session is expired, a new session will be generated and all of
// the data from the previous session will be lost. The new session will // the data from the previous session will be lost. The new session will
// be assigned a random, long string ID to uniquely identify it among // be assigned a random, long string ID to uniquely identify it among
// the application's current users. // the application's current users.
if (is_null($session) or (time() - $session['last_activity']) > ($config['lifetime'] * 60)) if (is_null(static::$session) or (time() - static::$session['last_activity']) > ($config['lifetime'] * 60))
{ {
$this->exists = false; static::$exists = false;
$session = array('id' => Str::random(40), 'data' => array()); static::$session = array('id' => Str::random(40), 'data' => array());
} }
$payload = new Payload($session);
// If a CSRF token is not present in the session, we will generate one. // If a CSRF token is not present in the session, we will generate one.
// These tokens are generated per session to protect against Cross-Site // These tokens are generated per session to protect against Cross-Site
// Request Forgery attacks on the application. It is up to the developer // Request Forgery attacks on the application. It is up to the developer
// to take advantage of them using the token methods on the Form class // to take advantage of them using the token methods on the Form class
// and the "csrf" route filter. // and the "csrf" route filter.
if ( ! $payload->has('csrf_token')) if ( ! static::has('csrf_token'))
{ {
$payload->put('csrf_token', Str::random(16)); static::put('csrf_token', Str::random(16));
} }
return $payload;
} }
/** /**
* Close the session handling for the request. * Determine if the session or flash data contains an item.
* *
* @param Payload $payload * @param string $key
* @param array $config * @return bool
* @param array $flash
* @return void
*/ */
public function close(Payload $payload, $config, $flash = array()) public static function has($key)
{ {
// If the session ID has been regenerated, we will need to inform the return ( ! is_null(static::get($key)));
// session driver that the session will need to be persisted to the }
// data store as a new session.
if ($payload->regenerated) $this->exists = false;
foreach ($flash as $key => $value) /**
* Get an item from the session.
*
* <code>
* // Get an item from the session
* $name = Session::get('name');
*
* // Return a default value if the item doesn't exist
* $name = Session::get('name', 'Taylor');
* </code>
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function get($key, $default = null)
{
foreach (array($key, ':old:'.$key, ':new:'.$key) as $possibility)
{ {
$payload->flash($key, $value); if (array_key_exists($possibility, static::$session['data']))
{
return static::$session['data'][$possibility];
}
} }
$this->driver->save($payload->age(), $config, $this->exists); return ($default instanceof Closure) ? call_user_func($default) : $default;
}
/**
* Write an item to the session.
*
* <code>
* // Write an item to the session
* Session::put('name', 'Taylor');
* </code>
*
* @param string $key
* @param mixed $value
* @return void
*/
public static function put($key, $value)
{
static::$session['data'][$key] = $value;
}
/**
* Write an item to the session flash data.
*
* Flash data only exists for the next request. After that, it will
* be removed from the session. Flash data is useful for temporary
* status or welcome messages.
*
* <code>
* // Flash an item to the session
* Session::flash('name', 'Taylor');
* </code>
*
* @param string $key
* @param mixed $value
* @return void
*/
public static function flash($key, $value)
{
static::put(':new:'.$key, $value);
}
$this->transporter->put($payload->session['id'], $config); /**
* Keep all of the session flash data from expiring at the end of the request.
*
* @return void
*/
public static function reflash()
{
static::replace(':old:', ':new:', array_keys(static::$session['data']));
}
// Some session drivers may implement the Sweeper interface, meaning the /**
// driver must do its garbage collection manually. Alternatively, some * Keep a session flash item from expiring at the end of the request.
// drivers such as APC and Memcached are not required to manually *
// clean up their sessions. * If a string is passed to the method, only that item will be kept.
if (mt_rand(1, $config['sweepage'][1]) <= $config['sweepage'][0] and $this->driver instanceof Drivers\Sweeper) * An array may also be passed to the method, in which case all
* items in the array will be kept.
*
* <code>
* // Keep a session flash item from expiring
* Session::keep('name');
* </code>
*
* @param string|array $key
* @return void
*/
public static function keep($key)
{
if (is_array($key)) return array_map(array($this, 'keep'), $key);
static::flash($key, static::get($key));
static::forget(':old:'.$key);
}
/**
* Remove an item from the session.
*
* @param string $key
* @return Driver
*/
public static function forget($key)
{
unset(static::$session['data'][$key]);
}
/**
* Remove all items from the session.
*
* @return void
*/
public static function flush()
{
static::$session['data'] = array();
}
/**
* Regenerate the session ID.
*
* @return void
*/
public static function regenerate()
{
static::$session['id'] = Str::random(40);
static::$regenerated = true;
static::$exists = false;
}
/**
* Age the session payload, preparing it for storage after a request.
*
* @return array
*/
protected static function age()
{
static::$session['last_activity'] = time();
// To age the data, we will forget all of the old keys and then
// rewrite the newly flashed items to have old keys, which will
// be available for the next request.
foreach (static::$session['data'] as $key => $value)
{ {
$this->driver->sweep(time() - ($config['lifetime'] * 60)); if (strpos($key, ':old:') === 0) static::forget($key);
} }
static::replace(':new:', ':old:', array_keys(static::$session['data']));
return static::$session;
} }
/** /**
* Dynamically pass methods to the current session payload. * Readdress the session data by performing a string replacement on the keys.
* *
* <code> * @param string $search
* // Retrieve an item from the session payload * @param string $replace
* $name = Session::get('name'); * @param array $keys
* @return void
*/
protected static function replace($search, $replace, $keys)
{
static::$session['data'] = array_combine(str_replace($search, $replace, $keys), array_values(static::$session['data']));
}
/**
* Close the session handling for the request.
* *
* // Write an item to the sessin payload * @param Drivers\Driver $driver
* Session::put('name', 'Taylor'); * @param Transporters\Transporter $transporter
* </code> * @param array $flash
* @return void
*/ */
public static function __callStatic($method, $parameters) public static function close(Driver $driver, Transporter $transporter, $flash = array())
{ {
if ( ! is_null(static::$payload)) $config = Config::$items['session'];
foreach ($flash as $key => $value)
{ {
return call_user_func_array(array(static::$payload, $method), $parameters); static::flash($key, $value);
} }
throw new \Exception("Call to undefined method [$method] on Session class."); $driver->save(static::age(), $config, static::$exists);
$transporter->put(static::$session['id'], $config);
// Some session drivers may implement the Sweeper interface, meaning the
// driver must do its garbage collection manually. Alternatively, some
// drivers such as APC and Memcached are not required to manually
// clean up their sessions.
if (mt_rand(1, $config['sweepage'][1]) <= $config['sweepage'][0] and $driver instanceof Drivers\Sweeper)
{
$driver->sweep(time() - ($config['lifetime'] * 60));
}
} }
} }
\ No newline at end of file
<?php namespace Laravel\Session; use Closure, Laravel\Str;
class Payload {
/**
* The raw session payload array.
*
* @var array
*/
public $session = array();
/**
* Indicates if the session ID has been regenerated.
*
* @var bool
*/
public $regenerated = false;
/**
* Create a new session container instance.
*
* @param array $session
* @return void
*/
public function __construct($session)
{
$this->session = $session;
}
/**
* Determine if the session or flash data contains an item.
*
* @param string $key
* @return bool
*/
public function has($key)
{
return ( ! is_null($this->get($key)));
}
/**
* Get an item from the session.
*
* <code>
* // Get an item from the session
* $name = Session::get('name');
*
* // Return a default value if the item doesn't exist
* $name = Session::get('name', 'Taylor');
* </code>
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function get($key, $default = null)
{
foreach (array($key, ':old:'.$key, ':new:'.$key) as $possibility)
{
if (array_key_exists($possibility, $this->session['data']))
{
return $this->session['data'][$possibility];
}
}
return ($default instanceof Closure) ? call_user_func($default) : $default;
}
/**
* Write an item to the session.
*
* <code>
* // Write an item to the session
* Session::put('name', 'Taylor');
* </code>
*
* @param string $key
* @param mixed $value
* @return Driver
*/
public function put($key, $value)
{
$this->session['data'][$key] = $value;
return $this;
}
/**
* Write an item to the session flash data.
*
* Flash data only exists for the next request. After that, it will
* be removed from the session. Flash data is useful for temporary
* status or welcome messages.
*
* <code>
* // Flash an item to the session
* Session::flash('name', 'Taylor');
* </code>
*
* @param string $key
* @param mixed $value
* @return Driver
*/
public function flash($key, $value)
{
$this->put(':new:'.$key, $value);
return $this;
}
/**
* Keep all of the session flash data from expiring at the end of the request.
*
* @return void
*/
public function reflash()
{
$this->replace(':old:', ':new:', array_keys($this->session['data']));
}
/**
* Keep a session flash item from expiring at the end of the request.
*
* If a string is passed to the method, only that item will be kept.
* An array may also be passed to the method, in which case all
* items in the array will be kept.
*
* <code>
* // Keep a session flash item from expiring
* Session::keep('name');
* </code>
*
* @param string|array $key
* @return void
*/
public function keep($key)
{
if (is_array($key)) return array_map(array($this, 'keep'), $key);
$this->flash($key, $this->get($key));
$this->forget(':old:'.$key);
}
/**
* Remove an item from the session.
*
* @param string $key
* @return Driver
*/
public function forget($key)
{
unset($this->session['data'][$key]);
}
/**
* Remove all items from the session.
*
* @return void
*/
public function flush()
{
$this->session['data'] = array();
}
/**
* Regenerate the session ID.
*
* @return void
*/
public function regenerate()
{
$this->session['id'] = Str::random(40);
$this->regenerated = true;
}
/**
* Age the session payload, preparing it for storage after a request.
*
* The session flash data will be aged and the last activity timestamp will
* be updated. The aged session array will be returned by the method.
*
* @return array
*/
public function age()
{
$this->session['last_activity'] = time();
// To age the data, we will forget all of the old keys and then
// rewrite the newly flashed items to have old keys, which will
// be available for the next request.
foreach ($this->session['data'] as $key => $value)
{
if (strpos($key, ':old:') === 0) $this->forget($key);
}
$this->replace(':new:', ':old:', array_keys($this->session['data']));
return $this->session;
}
/**
* Readdress the session data by performing a string replacement on the keys.
*
* @param string $search
* @param string $replace
* @param array $keys
* @return void
*/
private function replace($search, $replace, $keys)
{
$this->session['data'] = array_combine(str_replace($search, $replace, $keys), array_values($this->session['data']));
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment