Refactor Session Handling (make it more simple & handler are now handler again)

This commit is contained in:
Philipp Holzer 2019-12-11 20:30:31 +01:00
parent 02c40ad1cb
commit 1408908c84
No known key found for this signature in database
GPG Key ID: D8365C3D36B77D90
11 changed files with 143 additions and 140 deletions

View File

@ -59,11 +59,14 @@ class Session extends BaseObject
*/ */
public static function getRemoteContactID($uid) public static function getRemoteContactID($uid)
{ {
if (empty($_SESSION['remote'][$uid])) { /** @var ISession $session */
$session = self::getClass(ISession::class);
if (empty($session->get('remote')[$uid])) {
return false; return false;
} }
return $_SESSION['remote'][$uid]; return $session->get('remote')[$uid];
} }
/** /**
@ -74,11 +77,14 @@ class Session extends BaseObject
*/ */
public static function getUserIDForVisitorContactID($cid) public static function getUserIDForVisitorContactID($cid)
{ {
if (empty($_SESSION['remote'])) { /** @var ISession $session */
$session = self::getClass(ISession::class);
if (empty($session->get('remote'))) {
return false; return false;
} }
return array_search($cid, $_SESSION['remote']); return array_search($cid, $session->get('remote'));
} }
/** /**
@ -88,15 +94,18 @@ class Session extends BaseObject
*/ */
public static function setVisitorsContacts() public static function setVisitorsContacts()
{ {
$_SESSION['remote'] = []; /** @var ISession $session */
$session = self::getClass(ISession::class);
$remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($_SESSION['my_url']), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]); $session->set('remote', []);
$remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($session->get('my_url')), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
while ($contact = DBA::fetch($remote_contacts)) { while ($contact = DBA::fetch($remote_contacts)) {
if (($contact['uid'] == 0) || Contact::isBlockedByUser($contact['id'], $contact['uid'])) { if (($contact['uid'] == 0) || Contact::isBlockedByUser($contact['id'], $contact['uid'])) {
continue; continue;
} }
$_SESSION['remote'][$contact['uid']] = $contact['id']; $session->set('remote', [$contact['uid'] => $contact['id']]);
} }
DBA::close($remote_contacts); DBA::close($remote_contacts);
} }
@ -108,15 +117,9 @@ class Session extends BaseObject
*/ */
public static function isAuthenticated() public static function isAuthenticated()
{ {
if (empty($_SESSION['authenticated'])) { /** @var ISession $session */
return false; $session = self::getClass(ISession::class);
}
return $_SESSION['authenticated']; return $session->get('authenticated', false);
}
public static function delete()
{
self::getClass(ISession::class)->delete();
} }
} }

View File

@ -0,0 +1,76 @@
<?php
namespace Friendica\Core\Session;
use Friendica\Model\User\Cookie;
/**
* Contains the base methods for $_SESSION interaction
*/
class AbstractSession
{
/** @var Cookie */
protected $cookie;
public function __construct( Cookie $cookie)
{
$this->cookie = $cookie;
}
/**
* {@inheritDoc}
*/
public function start()
{
return $this;
}
/**
* {@inheritDoc}}
*/
public function exists(string $name)
{
return isset($_SESSION[$name]);
}
/**
* {@inheritDoc}
*/
public function get(string $name, $defaults = null)
{
return $_SESSION[$name] ?? $defaults;
}
/**
* {@inheritDoc}
*/
public function set(string $name, $value)
{
$_SESSION[$name] = $value;
}
/**
* {@inheritDoc}
*/
public function setMultiple(array $values)
{
$_SESSION = $values + $_SESSION;
}
/**
* {@inheritDoc}
*/
public function remove(string $name)
{
unset($_SESSION[$name]);
}
/**
* {@inheritDoc}
*/
public function clear()
{
$_SESSION = [];
}
}

View File

@ -1,11 +1,9 @@
<?php <?php
namespace Friendica\Core\Session; namespace Friendica\Core\Session\Handler;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\ICache;
use Friendica\Core\Config\Configuration;
use Friendica\Core\Session; use Friendica\Core\Session;
use Friendica\Model\User\Cookie;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use SessionHandlerInterface; use SessionHandlerInterface;
@ -14,7 +12,7 @@ use SessionHandlerInterface;
* *
* @author Hypolite Petovan <hypolite@mrpetovan.com> * @author Hypolite Petovan <hypolite@mrpetovan.com>
*/ */
final class Cache extends Native implements SessionHandlerInterface final class Cache implements SessionHandlerInterface
{ {
/** @var ICache */ /** @var ICache */
private $cache; private $cache;
@ -23,15 +21,11 @@ final class Cache extends Native implements SessionHandlerInterface
/** @var array The $_SERVER array */ /** @var array The $_SERVER array */
private $server; private $server;
public function __construct(Configuration $config, Cookie $cookie, ICache $cache, LoggerInterface $logger, array $server) public function __construct(ICache $cache, LoggerInterface $logger, array $server)
{ {
parent::__construct($config, $cookie);
$this->cache = $cache; $this->cache = $cache;
$this->logger = $logger; $this->logger = $logger;
$this->server = $server; $this->server = $server;
session_set_save_handler($this);
} }
public function open($save_path, $session_name) public function open($save_path, $session_name)

View File

@ -1,11 +1,9 @@
<?php <?php
namespace Friendica\Core\Session; namespace Friendica\Core\Session\Handler;
use Friendica\Core\Config\Configuration;
use Friendica\Core\Session; use Friendica\Core\Session;
use Friendica\Database\Database as DBA; use Friendica\Database\Database as DBA;
use Friendica\Model\User\Cookie;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use SessionHandlerInterface; use SessionHandlerInterface;
@ -14,7 +12,7 @@ use SessionHandlerInterface;
* *
* @author Hypolite Petovan <hypolite@mrpetovan.com> * @author Hypolite Petovan <hypolite@mrpetovan.com>
*/ */
final class Database extends Native implements SessionHandlerInterface final class Database implements SessionHandlerInterface
{ {
/** @var DBA */ /** @var DBA */
private $dba; private $dba;
@ -26,19 +24,15 @@ final class Database extends Native implements SessionHandlerInterface
/** /**
* DatabaseSessionHandler constructor. * DatabaseSessionHandler constructor.
* *
* @param Database $dba * @param DBA $dba
* @param LoggerInterface $logger * @param LoggerInterface $logger
* @param array $server * @param array $server
*/ */
public function __construct(Configuration $config, Cookie $cookie, DBA $dba, LoggerInterface $logger, array $server) public function __construct(DBA $dba, LoggerInterface $logger, array $server)
{ {
parent::__construct($config, $cookie);
$this->dba = $dba; $this->dba = $dba;
$this->logger = $logger; $this->logger = $logger;
$this->server = $server; $this->server = $server;
session_set_save_handler($this);
} }
public function open($save_path, $session_name) public function open($save_path, $session_name)

View File

@ -29,7 +29,8 @@ interface ISession
* Handle the case where session_start() hasn't been called and the super global isn't available. * Handle the case where session_start() hasn't been called and the super global isn't available.
* *
* @param string $name * @param string $name
* @param mixed $defaults * @param mixed $defaults
*
* @return mixed * @return mixed
*/ */
public function get(string $name, $defaults = null); public function get(string $name, $defaults = null);
@ -39,7 +40,7 @@ interface ISession
* Overrides value of existing key. * Overrides value of existing key.
* *
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
*/ */
public function set(string $name, $value); public function set(string $name, $value);
@ -63,9 +64,4 @@ interface ISession
* Clears the current session array * Clears the current session array
*/ */
public function clear(); public function clear();
/**
* Kills the "Friendica" cookie and all session data
*/
public function delete();
} }

View File

@ -2,7 +2,6 @@
namespace Friendica\Core\Session; namespace Friendica\Core\Session;
use Friendica\Core\Config\Configuration;
use Friendica\Model\User\Cookie; use Friendica\Model\User\Cookie;
/** /**
@ -10,19 +9,14 @@ use Friendica\Model\User\Cookie;
* *
* @todo after replacing the last direct $_SESSION call, use a internal array instead of the global variable * @todo after replacing the last direct $_SESSION call, use a internal array instead of the global variable
*/ */
final class Memory extends Native final class Memory extends AbstractSession implements ISession
{ {
public function __construct(Configuration $config, Cookie $cookie) public function __construct(Cookie $cookie)
{ {
$this->cookie = $cookie; parent::__construct($cookie);
}
public function start()
{
// Backward compatibility until all Session variables are replaced // Backward compatibility until all Session variables are replaced
// with the Session class // with the Session class
$_SESSION = []; $_SESSION = [];
$this->clear();
return $this;
} }
} }

View File

@ -2,29 +2,30 @@
namespace Friendica\Core\Session; namespace Friendica\Core\Session;
use Friendica\Core\Config\Configuration;
use Friendica\App; use Friendica\App;
use Friendica\Model\User\Cookie; use Friendica\Model\User\Cookie;
use SessionHandlerInterface;
/** /**
* The native Session class which uses the PHP internal Session function * The native Session class which uses the PHP internal Session functions
*/ */
class Native implements ISession final class Native extends AbstractSession implements ISession
{ {
/** @var Cookie */ public function __construct(App\BaseURL $baseURL, Cookie $cookie, SessionHandlerInterface $handler = null)
protected $cookie;
public function __construct(Configuration $config, Cookie $cookie)
{ {
parent::__construct($cookie);
ini_set('session.gc_probability', 50); ini_set('session.gc_probability', 50);
ini_set('session.use_only_cookies', 1); ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_httponly', 1); ini_set('session.cookie_httponly', (int)Cookie::HTTPONLY);
if ($config->get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL) { if ($baseURL->getSSLPolicy() == App\BaseURL::SSL_POLICY_FULL) {
ini_set('session.cookie_secure', 1); ini_set('session.cookie_secure', 1);
} }
$this->cookie = $cookie; if (isset($handler)) {
session_set_save_handler($handler);
}
} }
/** /**
@ -35,61 +36,4 @@ class Native implements ISession
session_start(); session_start();
return $this; return $this;
} }
/**
* {@inheritDoc}}
*/
public function exists(string $name)
{
return isset($_SESSION[$name]);
}
/**
* {@inheritDoc}
*/
public function get(string $name, $defaults = null)
{
return $_SESSION[$name] ?? $defaults;
}
/**
* {@inheritDoc}
*/
public function set(string $name, $value)
{
$_SESSION[$name] = $value;
}
/**
* {@inheritDoc}
*/
public function setMultiple(array $values)
{
$_SESSION = $values + $_SESSION;
}
/**
* {@inheritDoc}
*/
public function remove(string $name)
{
unset($_SESSION[$name]);
}
/**
* {@inheritDoc}
*/
public function clear()
{
$_SESSION = [];
}
/**
* @brief Kills the "Friendica" cookie and all session data
*/
public function delete()
{
$this->cookie->clear();
$_SESSION = [];
}
} }

View File

@ -19,18 +19,17 @@ use Psr\Log\LoggerInterface;
class SessionFactory class SessionFactory
{ {
/** @var string The plain, PHP internal session management */ /** @var string The plain, PHP internal session management */
const INTERNAL = 'native'; const HANDLER_NATIVE = 'native';
/** @var string Using the database for session management */ /** @var string Using the database for session management */
const DATABASE = 'database'; const HANDLER_DATABASE = 'database';
/** @var string Using the cache for session management */ /** @var string Using the cache for session management */
const CACHE = 'cache'; const HANDLER_CACHE = 'cache';
/** @var string A temporary cached session */
const MEMORY = 'memory'; const HANDLER_DEFAULT = self::HANDLER_DATABASE;
/** @var string The default type for Session management in case of no config */
const DEFAULT = self::DATABASE;
/** /**
* @param App\Mode $mode * @param App\Mode $mode
* @param App\BaseURL $baseURL
* @param Configuration $config * @param Configuration $config
* @param Cookie $cookie * @param Cookie $cookie
* @param Database $dba * @param Database $dba
@ -40,34 +39,33 @@ class SessionFactory
* *
* @return Session\ISession * @return Session\ISession
*/ */
public function createSession(App\Mode $mode, Configuration $config, Cookie $cookie, Database $dba, ICache $cache, LoggerInterface $logger, Profiler $profiler, array $server = []) public function createSession(App\Mode $mode, App\BaseURL $baseURL, Configuration $config, Cookie $cookie, Database $dba, ICache $cache, LoggerInterface $logger, Profiler $profiler, array $server = [])
{ {
$stamp1 = microtime(true); $stamp1 = microtime(true);
$session = null; $session = null;
try { try {
if ($mode->isInstall() || $mode->isBackend()) { if ($mode->isInstall() || $mode->isBackend()) {
$session = new Session\Memory($config, $cookie); $session = new Session\Memory($cookie);
} else { } else {
$session_handler = $config->get('system', 'session_handler', self::DEFAULT); $session_handler = $config->get('system', 'session_handler', self::HANDLER_DEFAULT);
$handler = null;
switch ($session_handler) { switch ($session_handler) {
case self::INTERNAL: case self::HANDLER_DATABASE:
$session = new Session\Native($config, $cookie); $handler = new Session\Handler\Database($dba, $logger, $server);
break; break;
case self::DATABASE: case self::HANDLER_CACHE:
default:
$session = new Session\Database($config, $cookie, $dba, $logger, $server);
break;
case self::CACHE:
// In case we're using the db as cache driver, use the native db session, not the cache // In case we're using the db as cache driver, use the native db session, not the cache
if ($config->get('system', 'cache_driver') === Cache::TYPE_DATABASE) { if ($config->get('system', 'cache_driver') === Cache::TYPE_DATABASE) {
$session = new Session\Database($config, $cookie, $dba, $logger, $server); $handler = new Session\Handler\Database($dba, $logger, $server);
} else { } else {
$session = new Session\Cache($config, $cookie, $cache, $logger, $server); $handler = new Session\Handler\Cache($cache, $logger, $server);
} }
break; break;
} }
$session = new Session\Native($baseURL, $cookie, $handler);
} }
} finally { } finally {
$profiler->saveTimestamp($stamp1, 'parser', System::callstack()); $profiler->saveTimestamp($stamp1, 'parser', System::callstack());

View File

@ -32,13 +32,13 @@ class Cookie
/** @var array The $_COOKIE array */ /** @var array The $_COOKIE array */
private $cookie; private $cookie;
public function __construct(Configuration $config, array $server = [], array $cookie = []) public function __construct(Configuration $config, App\BaseURL $baseURL, array $server = [], array $cookie = [])
{ {
if (!empty($server['REMOTE_ADDR'])) { if (!empty($server['REMOTE_ADDR'])) {
$this->remoteAddr = $server['REMOTE_ADDR']; $this->remoteAddr = $server['REMOTE_ADDR'];
} }
$this->sslEnabled = $config->get('system', 'ssl_policy') === App\BaseURL::SSL_POLICY_FULL; $this->sslEnabled = $baseURL->getSSLPolicy() === App\BaseURL::SSL_POLICY_FULL;
$this->sitePrivateKey = $config->get('system', 'site_prvkey'); $this->sitePrivateKey = $config->get('system', 'site_prvkey');
$authCookieDays = $config->get('system', 'auth_cookie_lifetime', $authCookieDays = $config->get('system', 'auth_cookie_lifetime',

View File

@ -33,7 +33,7 @@ class Logout extends BaseModule
} }
Hook::callAll("logging_out"); Hook::callAll("logging_out");
Session::delete(); Session::clear();
if ($visitor_home) { if ($visitor_home) {
System::externalRedirect($visitor_home); System::externalRedirect($visitor_home);

View File

@ -133,6 +133,10 @@ class dependencyCheck extends TestCase
public function testDevLogger() public function testDevLogger()
{ {
/** @var Configuration $config */
$config = $this->dice->create(Configuration::class);
$config->set('system', 'dlogfile', $this->root->url() . '/friendica.log');
/** @var LoggerInterface $logger */ /** @var LoggerInterface $logger */
$logger = $this->dice->create('$devLogger', ['dev']); $logger = $this->dice->create('$devLogger', ['dev']);