Merge pull request #7907 from nupplaphil/task/reduce_app_deps

Cleanup Session/Authentication
This commit is contained in:
Hypolite Petovan 2019-12-14 09:53:40 -05:00 committed by GitHub
commit 6e4a428c73
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 8791 additions and 7936 deletions

View file

@ -716,7 +716,6 @@ Here is a complete list of all hook callbacks with file locations (as of 24-Sep-
### src/Module/Login.php ### src/Module/Login.php
Hook::callAll('authenticate', $addon_auth);
Hook::callAll('login_hook', $o); Hook::callAll('login_hook', $o);
### src/Module/Logout.php ### src/Module/Logout.php
@ -740,6 +739,7 @@ Here is a complete list of all hook callbacks with file locations (as of 24-Sep-
### src/Core/Authentication.php ### src/Core/Authentication.php
Hook::callAll('logged_in', $a->user); Hook::callAll('logged_in', $a->user);
Hook::callAll('authenticate', $addon_auth);
### src/Core/Hook.php ### src/Core/Hook.php

View file

@ -12,6 +12,7 @@ use Friendica\Content\ContactSelector;
use Friendica\Content\Feature; use Friendica\Content\Feature;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\App\Authentication;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
@ -253,7 +254,9 @@ function api_login(App $a)
throw new UnauthorizedException("This API requires login"); throw new UnauthorizedException("This API requires login");
} }
Session::setAuthenticatedForUser($a, $record); /** @var Authentication $authentication */
$authentication = BaseObject::getClass(Authentication::class);
$authentication->setForUser($a, $record);
$_SESSION["allow_api"] = true; $_SESSION["allow_api"] = true;

View file

@ -22,5 +22,6 @@ $a = \Friendica\BaseObject::getApp();
$a->runFrontend( $a->runFrontend(
$dice->create(\Friendica\App\Module::class), $dice->create(\Friendica\App\Module::class),
$dice->create(\Friendica\App\Router::class), $dice->create(\Friendica\App\Router::class),
$dice->create(\Friendica\Core\Config\PConfiguration::class) $dice->create(\Friendica\Core\Config\PConfiguration::class),
$dice->create(\Friendica\App\Authentication::class)
); );

View file

@ -5,6 +5,8 @@
*/ */
use Friendica\App; use Friendica\App;
use Friendica\BaseObject;
use Friendica\App\Authentication;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger; use Friendica\Core\Logger;
@ -20,7 +22,9 @@ use Friendica\Util\XML;
function dfrn_poll_init(App $a) function dfrn_poll_init(App $a)
{ {
Login::sessionAuth(); /** @var Authentication $authentication */
$authentication = BaseObject::getClass(Authentication::class);
$authentication->withSession($a);
$dfrn_id = $_GET['dfrn_id'] ?? ''; $dfrn_id = $_GET['dfrn_id'] ?? '';
$type = ($_GET['type'] ?? '') ?: 'data'; $type = ($_GET['type'] ?? '') ?: 'data';

View file

@ -4,6 +4,8 @@
*/ */
use Friendica\App; use Friendica\App;
use Friendica\BaseObject;
use Friendica\App\Authentication;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger; use Friendica\Core\Logger;
@ -45,7 +47,9 @@ function openid_content(App $a) {
unset($_SESSION['openid']); unset($_SESSION['openid']);
Session::setAuthenticatedForUser($a, $user, true, true); /** @var Authentication $authentication */
$authentication = BaseObject::getClass(Authentication::class);
$authentication->setForUser($a, $user, true, true);
// just in case there was no return url set // just in case there was no return url set
// and we fell through // and we fell through

View file

@ -8,10 +8,12 @@ use Exception;
use Friendica\App\Arguments; use Friendica\App\Arguments;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\App\Page; use Friendica\App\Page;
use Friendica\App\Authentication;
use Friendica\Core\Config\Cache\ConfigCache; use Friendica\Core\Config\Cache\ConfigCache;
use Friendica\Core\Config\Configuration; use Friendica\Core\Config\Configuration;
use Friendica\Core\Config\PConfiguration; use Friendica\Core\Config\PConfiguration;
use Friendica\Core\L10n\L10n; use Friendica\Core\L10n\L10n;
use Friendica\Core\Session;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Theme; use Friendica\Core\Theme;
use Friendica\Database\Database; use Friendica\Database\Database;
@ -640,10 +642,11 @@ class App
* @param App\Module $module The determined module * @param App\Module $module The determined module
* @param App\Router $router * @param App\Router $router
* @param PConfiguration $pconfig * @param PConfiguration $pconfig
* @param Authentication $auth The Authentication backend of the node
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig) public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig, Authentication $auth)
{ {
$moduleName = $module->getName(); $moduleName = $module->getName();
@ -667,19 +670,11 @@ class App
System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString()); System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
} }
Core\Session::init();
Core\Hook::callAll('init_1'); Core\Hook::callAll('init_1');
} }
// Exclude the backend processes from the session management // Exclude the backend processes from the session management
if (!$this->mode->isBackend()) { if ($this->mode->isBackend()) {
$stamp1 = microtime(true);
session_start();
$this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
$this->l10n->setSessionVariable();
$this->l10n->setLangFromSession();
} else {
$_SESSION = [];
Core\Worker::executeIfIdle(); Core\Worker::executeIfIdle();
} }
@ -717,7 +712,7 @@ class App
Model\Profile::openWebAuthInit($token); Model\Profile::openWebAuthInit($token);
} }
Login::sessionAuth(); $auth->withSession($this);
if (empty($_SESSION['authenticated'])) { if (empty($_SESSION['authenticated'])) {
header('X-Account-Management-Status: none'); header('X-Account-Management-Status: none');
@ -796,22 +791,12 @@ class App
} }
/** /**
* Redirects to another module relative to the current Friendica base. * @deprecated 2019.12 use BaseUrl::redirect instead
* If you want to redirect to a external URL, use System::externalRedirectTo() * @see BaseURL::redirect()
*
* @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
* @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
*
* @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
*/ */
public function internalRedirect($toUrl = '', $ssl = false) public function internalRedirect($toUrl = '', $ssl = false)
{ {
if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) { $this->baseURL->redirect($toUrl, $ssl);
throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
}
$redirectTo = $this->baseURL->get($ssl) . '/' . ltrim($toUrl, '/');
Core\System::externalRedirect($redirectTo);
} }
/** /**
@ -827,7 +812,7 @@ class App
if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) { if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
Core\System::externalRedirect($toUrl); Core\System::externalRedirect($toUrl);
} else { } else {
$this->internalRedirect($toUrl); $this->baseURL->redirect($toUrl);
} }
} }
} }

413
src/App/Authentication.php Normal file
View file

@ -0,0 +1,413 @@
<?php
/**
* @file /src/Core/Authentication.php
*/
namespace Friendica\App;
use Exception;
use Friendica\App;
use Friendica\Core\Config\Configuration;
use Friendica\Core\Hook;
use Friendica\Core\PConfig;
use Friendica\Core\Session;
use Friendica\Core\System;
use Friendica\Database\Database;
use Friendica\Database\DBA;
use Friendica\Model\User;
use Friendica\Network\HTTPException;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use Friendica\Util\Strings;
use LightOpenID;
use Friendica\Core\L10n\L10n;
use Psr\Log\LoggerInterface;
/**
* Handle Authentification, Session and Cookies
*/
class Authentication
{
/** @var Configuration */
private $config;
/** @var App\BaseURL */
private $baseUrl;
/** @var L10n */
private $l10n;
/** @var Database */
private $dba;
/** @var LoggerInterface */
private $logger;
/** @var User\Cookie */
private $cookie;
/** @var Session\ISession */
private $session;
/**
* Authentication constructor.
*
* @param Configuration $config
* @param App\BaseURL $baseUrl
* @param L10n $l10n
* @param Database $dba
* @param LoggerInterface $logger
* @param User\Cookie $cookie
* @param Session\ISession $session
*/
public function __construct(Configuration $config, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session)
{
$this->config = $config;
$this->baseUrl = $baseUrl;
$this->l10n = $l10n;
$this->dba = $dba;
$this->logger = $logger;
$this->cookie = $cookie;
$this->session = $session;
}
/**
* @brief Tries to auth the user from the cookie or session
*
* @param App $a The Friendica Application context
*
* @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
* @throws Exception In case of general exceptions (like SQL Grammar)
*/
public function withSession(App $a)
{
$data = $this->cookie->getData();
// When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
if (isset($data->uid)) {
$user = $this->dba->selectFirst(
'user',
[],
[
'uid' => $data->uid,
'blocked' => false,
'account_expired' => false,
'account_removed' => false,
'verified' => true,
]
);
if ($this->dba->isResult($user)) {
if (!$this->cookie->check($data->hash,
$user['password'] ?? '',
$user['prvKey'] ?? '')) {
$this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
$this->session->delete();
$this->baseUrl->redirect();
}
// Renew the cookie
$this->cookie->set($user['uid'], $user['password'], $user['prvKey']);
// Do the authentification if not done by now
if (!$this->session->get('authenticated')) {
$this->setForUser($a, $user);
if ($this->config->get('system', 'paranoia')) {
$this->session->set('addr', $data->ip);
}
}
}
}
if ($this->session->get('authenticated')) {
if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
$contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
if ($this->dba->isResult($contact)) {
$a->contact = $contact;
}
}
if ($this->session->get('uid')) {
// already logged in user returning
$check = $this->config->get('system', 'paranoia');
// extra paranoia - if the IP changed, log them out
if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
$this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
'addr' => $this->session->get('addr'),
'remote_addr' => $_SERVER['REMOTE_ADDR']]
);
$this->session->delete();
$this->baseUrl->redirect();
}
$user = $this->dba->selectFirst(
'user',
[],
[
'uid' => $this->session->get('uid'),
'blocked' => false,
'account_expired' => false,
'account_removed' => false,
'verified' => true,
]
);
if (!$this->dba->isResult($user)) {
$this->session->delete();
$this->baseUrl->redirect();
}
// Make sure to refresh the last login time for the user if the user
// stays logged in for a long time, e.g. with "Remember Me"
$login_refresh = false;
if (!$this->session->get('last_login_date')) {
$this->session->set('last_login_date', DateTimeFormat::utcNow());
}
if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
$this->session->set('last_login_date', DateTimeFormat::utcNow());
$login_refresh = true;
}
$this->setForUser($a, $user, false, false, $login_refresh);
}
}
}
/**
* Attempts to authenticate using OpenId
*
* @param string $openid_url OpenID URL string
* @param bool $remember Whether to set the session remember flag
*
* @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
*/
public function withOpenId(string $openid_url, bool $remember)
{
$noid = $this->config->get('system', 'no_openid');
// if it's an email address or doesn't resolve to a URL, fail.
if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
notice($this->l10n->t('Login failed.') . EOL);
$this->baseUrl->redirect();
}
// Otherwise it's probably an openid.
try {
$openid = new LightOpenID($this->baseUrl->getHostname());
$openid->identity = $openid_url;
$this->session->set('openid', $openid_url);
$this->session->set('remember', $remember);
$openid->returnUrl = $this->baseUrl->get(true) . '/openid';
$openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
System::externalRedirect($openid->authUrl());
} catch (Exception $e) {
notice($this->l10n->t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '<br /><br >' . $this->l10n->t('The error message was:') . ' ' . $e->getMessage());
}
}
/**
* Attempts to authenticate using login/password
*
* @param App $a The Friendica Application context
* @param string $username User name
* @param string $password Clear password
* @param bool $remember Whether to set the session remember flag
*
* @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
* @throws Exception A general Exception (like SQL Grammar exceptions)
*/
public function withPassword(App $a, string $username, string $password, bool $remember)
{
$record = null;
$addon_auth = [
'username' => $username,
'password' => $password,
'authenticated' => 0,
'user_record' => null
];
/*
* An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
* Addons should never set 'authenticated' except to indicate success - as hooks may be chained
* and later addons should not interfere with an earlier one that succeeded.
*/
Hook::callAll('authenticate', $addon_auth);
try {
if ($addon_auth['authenticated']) {
$record = $addon_auth['user_record'];
if (empty($record)) {
throw new Exception($this->l10n->t('Login failed.'));
}
} else {
$record = $this->dba->selectFirst(
'user',
[],
['uid' => User::getIdFromPasswordAuthentication($username, $password)]
);
}
} catch (Exception $e) {
$this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
info($this->l10n->t('Login failed. Please check your credentials.' . EOL));
$this->baseUrl->redirect();
}
if (!$remember) {
$this->cookie->clear();
}
// if we haven't failed up this point, log them in.
$this->session->set('remember', $remember);
$this->session->set('last_login_date', DateTimeFormat::utcNow());
$openid_identity = $this->session->get('openid_identity');
$openid_server = $this->session->get('openid_server');
if (!empty($openid_identity) || !empty($openid_server)) {
$this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
}
$this->setForUser($a, $record, true, true);
$return_path = $this->session->get('return_path', '');
$this->session->remove('return_path');
$this->baseUrl->redirect($return_path);
}
/**
* @brief Sets the provided user's authenticated session
*
* @param App $a The Friendica application context
* @param array $user_record The current "user" record
* @param bool $login_initial
* @param bool $interactive
* @param bool $login_refresh
*
* @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
* @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
*/
public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
{
$this->session->setMultiple([
'uid' => $user_record['uid'],
'theme' => $user_record['theme'],
'mobile-theme' => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
'authenticated' => 1,
'page_flags' => $user_record['page-flags'],
'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
]);
Session::setVisitorsContacts();
$member_since = strtotime($user_record['register_date']);
$this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
if (strlen($user_record['timezone'])) {
date_default_timezone_set($user_record['timezone']);
$a->timezone = $user_record['timezone'];
}
$masterUid = $user_record['uid'];
if ($this->session->get('submanage')) {
$user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
if ($this->dba->isResult($user)) {
$masterUid = $user['uid'];
}
}
$a->identities = User::identities($masterUid);
if ($login_initial) {
$this->logger->info('auth_identities: ' . print_r($a->identities, true));
}
if ($login_refresh) {
$this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
}
$contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
if ($this->dba->isResult($contact)) {
$a->contact = $contact;
$a->cid = $contact['id'];
$this->session->set('cid', $a->cid);
}
header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
if ($login_initial || $login_refresh) {
$this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
// Set the login date for all identities of the user
$this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
['parent-uid' => $masterUid, 'account_removed' => false]);
}
if ($login_initial) {
/*
* If the user specified to remember the authentication, then set a cookie
* that expires after one week (the default is when the browser is closed).
* The cookie will be renewed automatically.
* The week ensures that sessions will expire after some inactivity.
*/;
if ($this->session->get('remember')) {
$a->getLogger()->info('Injecting cookie for remembered user ' . $user_record['nickname']);
$this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvKey']);
$this->session->remove('remember');
}
}
$this->twoFactorCheck($user_record['uid'], $a);
if ($interactive) {
if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
info($this->l10n->t('Welcome %s', $user_record['username']));
info($this->l10n->t('Please upload a profile photo.'));
$this->baseUrl->redirect('profile_photo/new');
} else {
info($this->l10n->t("Welcome back %s", $user_record['username']));
}
}
$a->user = $user_record;
if ($login_initial) {
Hook::callAll('logged_in', $a->user);
if ($a->module !== 'home' && $this->session->exists('return_path')) {
$this->baseUrl->redirect($this->session->get('return_path'));
}
}
}
/**
* @param int $uid The User Identified
* @param App $a The Friendica Application context
*
* @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
*/
private function twoFactorCheck(int $uid, App $a)
{
// Check user setting, if 2FA disabled return
if (!PConfig::get($uid, '2fa', 'verified')) {
return;
}
// Check current path, if 2fa authentication module return
if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
return;
}
// Case 1: 2FA session present and valid: return
if ($this->session->get('2fa')) {
return;
}
// Case 2: No valid 2FA session: redirect to code verification page
if ($a->isAjax()) {
throw new HTTPException\ForbiddenException();
} else {
$a->internalRedirect('2fa');
}
}
}

View file

@ -3,8 +3,10 @@
namespace Friendica\App; namespace Friendica\App;
use Friendica\Core\Config\Configuration; use Friendica\Core\Config\Configuration;
use Friendica\Core\System;
use Friendica\Util\Network; use Friendica\Util\Network;
use Friendica\Util\Strings; use Friendica\Util\Strings;
use Friendica\Network\HTTPException;
/** /**
* A class which checks and contains the basic * A class which checks and contains the basic
@ -414,4 +416,23 @@ class BaseURL
return $url; return $url;
} }
} }
/**
* Redirects to another module relative to the current Friendica base URL.
* If you want to redirect to a external URL, use System::externalRedirectTo()
*
* @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
* @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
*
* @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
*/
public function redirect($toUrl = '', $ssl = false)
{
if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
}
$redirectTo = $this->get($ssl) . '/' . ltrim($toUrl, '/');
System::externalRedirect($redirectTo);
}
} }

View file

@ -1,95 +0,0 @@
<?php
/**
* @file /src/Core/Authentication.php
*/
namespace Friendica\Core;
use Friendica\App;
use Friendica\BaseObject;
use Friendica\Network\HTTPException\ForbiddenException;
/**
* Handle Authentification, Session and Cookies
*/
class Authentication extends BaseObject
{
/**
* @brief Calculate the hash that is needed for the "Friendica" cookie
*
* @param array $user Record from "user" table
*
* @return string Hashed data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function getCookieHashForUser($user)
{
return hash_hmac(
"sha256",
hash_hmac("sha256", $user["password"], $user["prvkey"]),
Config::get("system", "site_prvkey")
);
}
/**
* @brief Set the "Friendica" cookie
*
* @param int $time
* @param array $user Record from "user" table
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function setCookie($time, $user = [])
{
if ($time != 0) {
$time = $time + time();
}
if ($user) {
$value = json_encode([
"uid" => $user["uid"],
"hash" => self::getCookieHashForUser($user),
"ip" => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
]);
} else {
$value = "";
}
setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL), true);
}
/**
* @brief Kills the "Friendica" cookie and all session data
*/
public static function deleteSession()
{
self::setCookie(-3600); // make sure cookie is deleted on browser close, as a security measure
session_unset();
session_destroy();
}
public static function twoFactorCheck($uid, App $a)
{
// Check user setting, if 2FA disabled return
if (!PConfig::get($uid, '2fa', 'verified')) {
return;
}
// Check current path, if 2fa authentication module return
if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
return;
}
// Case 1: 2FA session present and valid: return
if (Session::get('2fa')) {
return;
}
// Case 2: No valid 2FA session: redirect to code verification page
if ($a->isAjax()) {
throw new ForbiddenException();
} else {
$a->internalRedirect('2fa');
}
}
}

View file

@ -4,7 +4,7 @@ namespace Friendica\Core\L10n;
use Friendica\Core\Config\Configuration; use Friendica\Core\Config\Configuration;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Session; use Friendica\Core\Session\ISession;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Util\Strings; use Friendica\Util\Strings;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
@ -53,12 +53,14 @@ class L10n
*/ */
private $logger; private $logger;
public function __construct(Configuration $config, Database $dba, LoggerInterface $logger, array $server, array $get) public function __construct(Configuration $config, Database $dba, LoggerInterface $logger, ISession $session, array $server, array $get)
{ {
$this->dba = $dba; $this->dba = $dba;
$this->logger = $logger; $this->logger = $logger;
$this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', 'en'))); $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', 'en')));
$this->setSessionVariable($session);
$this->setLangFromSession($session);
} }
/** /**
@ -74,28 +76,28 @@ class L10n
/** /**
* Sets the language session variable * Sets the language session variable
*/ */
public function setSessionVariable() private function setSessionVariable(ISession $session)
{ {
if (Session::get('authenticated') && !Session::get('language')) { if ($session->get('authenticated') && !$session->get('language')) {
$_SESSION['language'] = $this->lang; $session->set('language', $this->lang);
// we haven't loaded user data yet, but we need user language // we haven't loaded user data yet, but we need user language
if (Session::get('uid')) { if ($session->get('uid')) {
$user = $this->dba->selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]); $user = $this->dba->selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
if ($this->dba->isResult($user)) { if ($this->dba->isResult($user)) {
$_SESSION['language'] = $user['language']; $session->set('language', $user['language']);
} }
} }
} }
if (isset($_GET['lang'])) { if (isset($_GET['lang'])) {
Session::set('language', $_GET['lang']); $session->set('language', $_GET['lang']);
} }
} }
public function setLangFromSession() private function setLangFromSession(ISession $session)
{ {
if (Session::get('language') !== $this->lang) { if ($session->get('language') !== $this->lang) {
$this->loadTranslationTable(Session::get('language')); $this->loadTranslationTable($session->get('language'));
} }
} }

View file

@ -5,13 +5,10 @@
*/ */
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\App; use Friendica\BaseObject;
use Friendica\Core\Session\CacheSessionHandler; use Friendica\Core\Session\ISession;
use Friendica\Core\Session\DatabaseSessionHandler;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Model\User;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Strings; use Friendica\Util\Strings;
/** /**
@ -19,200 +16,39 @@ use Friendica\Util\Strings;
* *
* @author Hypolite Petovan <hypolite@mrpetovan.com> * @author Hypolite Petovan <hypolite@mrpetovan.com>
*/ */
class Session class Session extends BaseObject
{ {
public static $exists = false; public static $exists = false;
public static $expire = 180000; public static $expire = 180000;
public static function init()
{
ini_set('session.gc_probability', 50);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_httponly', 1);
if (Config::get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL) {
ini_set('session.cookie_secure', 1);
}
$session_handler = Config::get('system', 'session_handler', 'database');
if ($session_handler != 'native') {
if ($session_handler == 'cache' && Config::get('system', 'cache_driver', 'database') != 'database') {
$SessionHandler = new CacheSessionHandler();
} else {
$SessionHandler = new DatabaseSessionHandler();
}
session_set_save_handler($SessionHandler);
}
}
public static function exists($name) public static function exists($name)
{ {
return isset($_SESSION[$name]); return self::getClass(ISession::class)->exists($name);
} }
/**
* Retrieves a key from the session super global or the defaults if the key is missing or the value is falsy.
*
* Handle the case where session_start() hasn't been called and the super global isn't available.
*
* @param string $name
* @param mixed $defaults
* @return mixed
*/
public static function get($name, $defaults = null) public static function get($name, $defaults = null)
{ {
return $_SESSION[$name] ?? $defaults; return self::getClass(ISession::class)->get($name, $defaults);
} }
/**
* Sets a single session variable.
* Overrides value of existing key.
*
* @param string $name
* @param mixed $value
*/
public static function set($name, $value) public static function set($name, $value)
{ {
$_SESSION[$name] = $value; self::getClass(ISession::class)->set($name, $value);
} }
/**
* Sets multiple session variables.
* Overrides values for existing keys.
*
* @param array $values
*/
public static function setMultiple(array $values) public static function setMultiple(array $values)
{ {
$_SESSION = $values + $_SESSION; self::getClass(ISession::class)->setMultiple($values);
} }
/**
* Removes a session variable.
* Ignores missing keys.
*
* @param $name
*/
public static function remove($name) public static function remove($name)
{ {
unset($_SESSION[$name]); self::getClass(ISession::class)->remove($name);
} }
/**
* Clears the current session array
*/
public static function clear() public static function clear()
{ {
$_SESSION = []; self::getClass(ISession::class)->clear();
}
/**
* @brief Sets the provided user's authenticated session
*
* @param App $a
* @param array $user_record
* @param bool $login_initial
* @param bool $interactive
* @param bool $login_refresh
* @throws \Friendica\Network\HTTPException\ForbiddenException
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function setAuthenticatedForUser(App $a, array $user_record, $login_initial = false, $interactive = false, $login_refresh = false)
{
self::setMultiple([
'uid' => $user_record['uid'],
'theme' => $user_record['theme'],
'mobile-theme' => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
'authenticated' => 1,
'page_flags' => $user_record['page-flags'],
'my_url' => $a->getBaseURL() . '/profile/' . $user_record['nickname'],
'my_address' => $user_record['nickname'] . '@' . substr($a->getBaseURL(), strpos($a->getBaseURL(), '://') + 3),
'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
]);
self::setVisitorsContacts();
$member_since = strtotime($user_record['register_date']);
self::set('new_member', time() < ($member_since + ( 60 * 60 * 24 * 14)));
if (strlen($user_record['timezone'])) {
date_default_timezone_set($user_record['timezone']);
$a->timezone = $user_record['timezone'];
}
$masterUid = $user_record['uid'];
if (self::get('submanage')) {
$user = DBA::selectFirst('user', ['uid'], ['uid' => self::get('submanage')]);
if (DBA::isResult($user)) {
$masterUid = $user['uid'];
}
}
$a->identities = User::identities($masterUid);
if ($login_initial) {
$a->getLogger()->info('auth_identities: ' . print_r($a->identities, true));
}
if ($login_refresh) {
$a->getLogger()->info('auth_identities refresh: ' . print_r($a->identities, true));
}
$contact = DBA::selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
if (DBA::isResult($contact)) {
$a->contact = $contact;
$a->cid = $contact['id'];
self::set('cid', $a->cid);
}
header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
if ($login_initial || $login_refresh) {
DBA::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
// Set the login date for all identities of the user
DBA::update('user', ['login_date' => DateTimeFormat::utcNow()],
['parent-uid' => $masterUid, 'account_removed' => false]);
}
if ($login_initial) {
/*
* If the user specified to remember the authentication, then set a cookie
* that expires after one week (the default is when the browser is closed).
* The cookie will be renewed automatically.
* The week ensures that sessions will expire after some inactivity.
*/
;
if (self::get('remember')) {
$a->getLogger()->info('Injecting cookie for remembered user ' . $user_record['nickname']);
Authentication::setCookie(604800, $user_record);
self::remove('remember');
}
}
Authentication::twoFactorCheck($user_record['uid'], $a);
if ($interactive) {
if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
info(L10n::t('Welcome %s', $user_record['username']));
info(L10n::t('Please upload a profile photo.'));
$a->internalRedirect('profile_photo/new');
} else {
info(L10n::t("Welcome back %s", $user_record['username']));
}
}
$a->user = $user_record;
if ($login_initial) {
Hook::callAll('logged_in', $a->user);
if ($a->module !== 'home' && self::exists('return_path')) {
$a->internalRedirect(self::get('return_path'));
}
}
} }
/** /**
@ -223,11 +59,14 @@ class Session
*/ */
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];
} }
/** /**
@ -238,11 +77,14 @@ class Session
*/ */
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'));
} }
/** /**
@ -252,15 +94,18 @@ class Session
*/ */
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);
} }
@ -272,10 +117,9 @@ class Session
*/ */
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);
} }
} }

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,93 +0,0 @@
<?php
namespace Friendica\Core\Session;
use Friendica\BaseObject;
use Friendica\Core\Logger;
use Friendica\Core\Session;
use Friendica\Database\DBA;
use SessionHandlerInterface;
/**
* SessionHandler using database
*
* @author Hypolite Petovan <hypolite@mrpetovan.com>
*/
class DatabaseSessionHandler extends BaseObject implements SessionHandlerInterface
{
public function open($save_path, $session_name)
{
return true;
}
public function read($session_id)
{
if (empty($session_id)) {
return '';
}
$session = DBA::selectFirst('session', ['data'], ['sid' => $session_id]);
if (DBA::isResult($session)) {
Session::$exists = true;
return $session['data'];
}
Logger::notice('no data for session', ['session_id' => $session_id, 'uri' => $_SERVER['REQUEST_URI']]);
return '';
}
/**
* @brief Standard PHP session write callback
*
* This callback updates the DB-stored session data and/or the expiration depending
* on the case. Uses the Session::expire global for existing session, 5 minutes
* for newly created session.
*
* @param string $session_id Session ID with format: [a-z0-9]{26}
* @param string $session_data Serialized session data
* @return boolean Returns false if parameters are missing, true otherwise
* @throws \Exception
*/
public function write($session_id, $session_data)
{
if (!$session_id) {
return false;
}
if (!$session_data) {
return true;
}
$expire = time() + Session::$expire;
$default_expire = time() + 300;
if (Session::$exists) {
$fields = ['data' => $session_data, 'expire' => $expire];
$condition = ["`sid` = ? AND (`data` != ? OR `expire` != ?)", $session_id, $session_data, $expire];
DBA::update('session', $fields, $condition);
} else {
$fields = ['sid' => $session_id, 'expire' => $default_expire, 'data' => $session_data];
DBA::insert('session', $fields);
}
return true;
}
public function close()
{
return true;
}
public function destroy($id)
{
DBA::delete('session', ['sid' => $id]);
return true;
}
public function gc($maxlifetime)
{
DBA::delete('session', ["`expire` < ?", time()]);
return true;
}
}

View file

@ -1,11 +1,10 @@
<?php <?php
namespace Friendica\Core\Session; namespace Friendica\Core\Session\Handler;
use Friendica\BaseObject; use Friendica\Core\Cache\ICache;
use Friendica\Core\Cache;
use Friendica\Core\Logger;
use Friendica\Core\Session; use Friendica\Core\Session;
use Psr\Log\LoggerInterface;
use SessionHandlerInterface; use SessionHandlerInterface;
/** /**
@ -13,8 +12,22 @@ use SessionHandlerInterface;
* *
* @author Hypolite Petovan <hypolite@mrpetovan.com> * @author Hypolite Petovan <hypolite@mrpetovan.com>
*/ */
class CacheSessionHandler extends BaseObject implements SessionHandlerInterface final class Cache implements SessionHandlerInterface
{ {
/** @var ICache */
private $cache;
/** @var LoggerInterface */
private $logger;
/** @var array The $_SERVER array */
private $server;
public function __construct(ICache $cache, LoggerInterface $logger, array $server)
{
$this->cache = $cache;
$this->logger = $logger;
$this->server = $server;
}
public function open($save_path, $session_name) public function open($save_path, $session_name)
{ {
return true; return true;
@ -26,13 +39,13 @@ class CacheSessionHandler extends BaseObject implements SessionHandlerInterface
return ''; return '';
} }
$data = Cache::get('session:' . $session_id); $data = $this->cache->get('session:' . $session_id);
if (!empty($data)) { if (!empty($data)) {
Session::$exists = true; Session::$exists = true;
return $data; return $data;
} }
Logger::notice('no data for session', ['session_id' => $session_id, 'uri' => $_SERVER['REQUEST_URI']]); $this->logger->notice('no data for session', ['session_id' => $session_id, 'uri' => $this->server['REQUEST_URI'] ?? '']);
return ''; return '';
} }
@ -46,6 +59,7 @@ class CacheSessionHandler extends BaseObject implements SessionHandlerInterface
* *
* @param string $session_id Session ID with format: [a-z0-9]{26} * @param string $session_id Session ID with format: [a-z0-9]{26}
* @param string $session_data Serialized session data * @param string $session_data Serialized session data
*
* @return boolean Returns false if parameters are missing, true otherwise * @return boolean Returns false if parameters are missing, true otherwise
* @throws \Exception * @throws \Exception
*/ */
@ -59,9 +73,7 @@ class CacheSessionHandler extends BaseObject implements SessionHandlerInterface
return true; return true;
} }
$return = Cache::set('session:' . $session_id, $session_data, Session::$expire); return $this->cache->set('session:' . $session_id, $session_data, Session::$expire);
return $return;
} }
public function close() public function close()
@ -71,9 +83,7 @@ class CacheSessionHandler extends BaseObject implements SessionHandlerInterface
public function destroy($id) public function destroy($id)
{ {
$return = Cache::delete('session:' . $id); return $this->cache->delete('session:' . $id);
return $return;
} }
public function gc($maxlifetime) public function gc($maxlifetime)

View file

@ -0,0 +1,112 @@
<?php
namespace Friendica\Core\Session\Handler;
use Friendica\Core\Session;
use Friendica\Database\Database as DBA;
use Psr\Log\LoggerInterface;
use SessionHandlerInterface;
/**
* SessionHandler using database
*
* @author Hypolite Petovan <hypolite@mrpetovan.com>
*/
final class Database implements SessionHandlerInterface
{
/** @var DBA */
private $dba;
/** @var LoggerInterface */
private $logger;
/** @var array The $_SERVER variable */
private $server;
/**
* DatabaseSessionHandler constructor.
*
* @param DBA $dba
* @param LoggerInterface $logger
* @param array $server
*/
public function __construct(DBA $dba, LoggerInterface $logger, array $server)
{
$this->dba = $dba;
$this->logger = $logger;
$this->server = $server;
}
public function open($save_path, $session_name)
{
return true;
}
public function read($session_id)
{
if (empty($session_id)) {
return '';
}
$session = $this->dba->selectFirst('session', ['data'], ['sid' => $session_id]);
if ($this->dba->isResult($session)) {
Session::$exists = true;
return $session['data'];
}
$this->logger->notice('no data for session', ['session_id' => $session_id, 'uri' => $this->server['REQUEST_URI'] ?? '']);
return '';
}
/**
* @brief Standard PHP session write callback
*
* This callback updates the DB-stored session data and/or the expiration depending
* on the case. Uses the Session::expire global for existing session, 5 minutes
* for newly created session.
*
* @param string $session_id Session ID with format: [a-z0-9]{26}
* @param string $session_data Serialized session data
*
* @return boolean Returns false if parameters are missing, true otherwise
* @throws \Exception
*/
public function write($session_id, $session_data)
{
if (!$session_id) {
return false;
}
if (!$session_data) {
return true;
}
$expire = time() + Session::$expire;
$default_expire = time() + 300;
if (Session::$exists) {
$fields = ['data' => $session_data, 'expire' => $expire];
$condition = ["`sid` = ? AND (`data` != ? OR `expire` != ?)", $session_id, $session_data, $expire];
$this->dba->update('session', $fields, $condition);
} else {
$fields = ['sid' => $session_id, 'expire' => $default_expire, 'data' => $session_data];
$this->dba->insert('session', $fields);
}
return true;
}
public function close()
{
return true;
}
public function destroy($id)
{
return $this->dba->delete('session', ['sid' => $id]);
}
public function gc($maxlifetime)
{
return $this->dba->delete('session', ["`expire` < ?", time()]);
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace Friendica\Core\Session;
/**
* Contains all global supported Session methods
*/
interface ISession
{
/**
* Start the current session
*
* @return self The own Session instance
*/
public function start();
/**
* Checks if the key exists in this session
*
* @param string $name
*
* @return boolean True, if it exists
*/
public function exists(string $name);
/**
* Retrieves a key from the session super global or the defaults if the key is missing or the value is falsy.
*
* Handle the case where session_start() hasn't been called and the super global isn't available.
*
* @param string $name
* @param mixed $defaults
*
* @return mixed
*/
public function get(string $name, $defaults = null);
/**
* Sets a single session variable.
* Overrides value of existing key.
*
* @param string $name
* @param mixed $value
*/
public function set(string $name, $value);
/**
* Sets multiple session variables.
* Overrides values for existing keys.
*
* @param array $values
*/
public function setMultiple(array $values);
/**
* Removes a session variable.
* Ignores missing keys.
*
* @param string $name
*/
public function remove(string $name);
/**
* Clears the current session array
*/
public function clear();
}

View file

@ -0,0 +1,22 @@
<?php
namespace Friendica\Core\Session;
use Friendica\Model\User\Cookie;
/**
* Usable for backend processes (daemon/worker) and testing
*
* @todo after replacing the last direct $_SESSION call, use a internal array instead of the global variable
*/
final class Memory extends AbstractSession implements ISession
{
public function __construct(Cookie $cookie)
{
parent::__construct($cookie);
// Backward compatibility until all Session variables are replaced
// with the Session class
$_SESSION = [];
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace Friendica\Core\Session;
use Friendica\App;
use Friendica\Model\User\Cookie;
use SessionHandlerInterface;
/**
* The native Session class which uses the PHP internal Session functions
*/
final class Native extends AbstractSession implements ISession
{
public function __construct(App\BaseURL $baseURL, Cookie $cookie, SessionHandlerInterface $handler = null)
{
parent::__construct($cookie);
ini_set('session.gc_probability', 50);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_httponly', (int)Cookie::HTTPONLY);
if ($baseURL->getSSLPolicy() == App\BaseURL::SSL_POLICY_FULL) {
ini_set('session.cookie_secure', 1);
}
if (isset($handler)) {
session_set_save_handler($handler);
}
}
/**
* {@inheritDoc}
*/
public function start()
{
session_start();
return $this;
}
}

View file

@ -0,0 +1,75 @@
<?php
namespace Friendica\Factory;
use Friendica\App;
use Friendica\Core\Cache\Cache;
use Friendica\Core\Cache\ICache;
use Friendica\Core\Config\Configuration;
use Friendica\Core\Session;
use Friendica\Core\System;
use Friendica\Database\Database;
use Friendica\Model\User\Cookie;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
/**
* Factory for creating a valid Session for this run
*/
class SessionFactory
{
/** @var string The plain, PHP internal session management */
const HANDLER_NATIVE = 'native';
/** @var string Using the database for session management */
const HANDLER_DATABASE = 'database';
/** @var string Using the cache for session management */
const HANDLER_CACHE = 'cache';
const HANDLER_DEFAULT = self::HANDLER_DATABASE;
/**
* @param App\Mode $mode
* @param App\BaseURL $baseURL
* @param Configuration $config
* @param Cookie $cookie
* @param Database $dba
* @param ICache $cache
* @param LoggerInterface $logger
* @param array $server
*
* @return Session\ISession
*/
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);
$session = null;
try {
if ($mode->isInstall() || $mode->isBackend()) {
$session = new Session\Memory($cookie);
} else {
$session_handler = $config->get('system', 'session_handler', self::HANDLER_DEFAULT);
$handler = null;
switch ($session_handler) {
case self::HANDLER_DATABASE:
$handler = new Session\Handler\Database($dba, $logger, $server);
break;
case self::HANDLER_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) {
$handler = new Session\Handler\Database($dba, $logger, $server);
} else {
$handler = new Session\Handler\Cache($cache, $logger, $server);
}
break;
}
$session = new Session\Native($baseURL, $cookie, $handler);
}
} finally {
$profiler->saveTimestamp($stamp1, 'parser', System::callstack());
return $session;
}
}
}

157
src/Model/User/Cookie.php Normal file
View file

@ -0,0 +1,157 @@
<?php
namespace Friendica\Model\User;
use Friendica\App;
use Friendica\Core\Config\Configuration;
/**
* Interacting with the Friendica Cookie of a user
*/
class Cookie
{
/** @var int Default expire duration in days */
const DEFAULT_EXPIRE = 7;
/** @var string The name of the Friendica cookie */
const NAME = 'Friendica';
/** @var string The path of the Friendica cookie */
const PATH = '/';
/** @var string The domain name of the Friendica cookie */
const DOMAIN = '';
/** @var bool True, if the cookie should only be accessible through HTTP */
const HTTPONLY = true;
/** @var string The remote address of this node */
private $remoteAddr = '0.0.0.0';
/** @var bool True, if the connection is ssl enabled */
private $sslEnabled = false;
/** @var string The private key of this Friendica node */
private $sitePrivateKey;
/** @var int The default cookie lifetime */
private $lifetime = self::DEFAULT_EXPIRE * 24 * 60 * 60;
/** @var array The $_COOKIE array */
private $cookie;
public function __construct(Configuration $config, App\BaseURL $baseURL, array $server = [], array $cookie = [])
{
if (!empty($server['REMOTE_ADDR'])) {
$this->remoteAddr = $server['REMOTE_ADDR'];
}
$this->sslEnabled = $baseURL->getSSLPolicy() === App\BaseURL::SSL_POLICY_FULL;
$this->sitePrivateKey = $config->get('system', 'site_prvkey');
$authCookieDays = $config->get('system', 'auth_cookie_lifetime',
self::DEFAULT_EXPIRE);
$this->lifetime = $authCookieDays * 24 * 60 * 60;
$this->cookie = $cookie;
}
/**
* Checks if the Friendica cookie is set for a user
*
* @param string $hash The cookie hash
* @param string $password The user password
* @param string $privateKey The private Key of the user
*
* @return boolean True, if the cookie is set
*
*/
public function check(string $hash, string $password, string $privateKey)
{
return hash_equals(
$this->getHash($password, $privateKey),
$hash
);
}
/**
* Set the Friendica cookie for a user
*
* @param int $uid The user id
* @param string $password The user password
* @param string $privateKey The user private key
* @param int|null $seconds optional the seconds
*
* @return bool
*/
public function set(int $uid, string $password, string $privateKey, int $seconds = null)
{
if (!isset($seconds)) {
$seconds = $this->lifetime + time();
} elseif (isset($seconds) && $seconds != 0) {
$seconds = $seconds + time();
}
$value = json_encode([
'uid' => $uid,
'hash' => $this->getHash($password, $privateKey),
'ip' => $this->remoteAddr,
]);
return $this->setCookie(self::NAME, $value, $seconds, $this->sslEnabled);
}
/**
* Returns the data of the Friendicas user cookie
*
* @return mixed|null The JSON data, null if not set
*/
public function getData()
{
// When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
if (isset($this->cookie[self::NAME])) {
$data = json_decode($this->cookie[self::NAME]);
if (!empty($data)) {
return $data;
}
}
return null;
}
/**
* Clears the Friendica cookie of this user after leaving the page
*/
public function clear()
{
// make sure cookie is deleted on browser close, as a security measure
return $this->setCookie(self::NAME, '', -3600, $this->sslEnabled);
}
/**
* Calculate the hash that is needed for the Friendica cookie
*
* @param string $password The user password
* @param string $privateKey The private key of the user
*
* @return string Hashed data
*/
private function getHash(string $password, string $privateKey)
{
return hash_hmac(
'sha256',
hash_hmac('sha256', $password, $privateKey),
$this->sitePrivateKey
);
}
/**
* Send a cookie - protected, internal function for test-mocking possibility
*
* @link https://php.net/manual/en/function.setcookie.php
*
* @param string $name
* @param string $value [optional]
* @param int $expire [optional]
* @param bool $secure [optional]
*
* @return bool If output exists prior to calling this function,
*
*/
protected function setCookie(string $name, string $value = null, int $expire = null,
bool $secure = null)
{
return setcookie($name, $value, $expire, self::PATH, self::DOMAIN, $secure, self::HTTPONLY);
}
}

View file

@ -3,6 +3,7 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\App\Authentication;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
@ -79,7 +80,9 @@ class Delegation extends BaseModule
Session::clear(); Session::clear();
Session::setAuthenticatedForUser(self::getApp(), $user, true, true); /** @var Authentication $authentication */
$authentication = self::getClass(Authentication::class);
$authentication->setForUser(self::getApp(), $user, true, true);
if ($limited_id) { if ($limited_id) {
Session::set('submanage', $original_id); Session::set('submanage', $original_id);

View file

@ -6,22 +6,14 @@
namespace Friendica\Module; namespace Friendica\Module;
use Exception;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\Authentication; use Friendica\App\Authentication;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Session; use Friendica\Core\Session;
use Friendica\Core\System;
use Friendica\Database\DBA;
use Friendica\Model\User;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use Friendica\Util\Strings; use Friendica\Util\Strings;
use LightOpenID;
/** /**
* Login module * Login module
@ -43,11 +35,8 @@ class Login extends BaseModule
public static function post(array $parameters = []) public static function post(array $parameters = [])
{ {
$openid_identity = Session::get('openid_identity');
$openid_server = Session::get('openid_server');
$return_path = Session::get('return_path'); $return_path = Session::get('return_path');
session_unset(); Session::clear();
Session::set('return_path', $return_path); Session::set('return_path', $return_path);
// OpenId Login // OpenId Login
@ -58,228 +47,23 @@ class Login extends BaseModule
) { ) {
$openid_url = trim(($_POST['openid_url'] ?? '') ?: $_POST['username']); $openid_url = trim(($_POST['openid_url'] ?? '') ?: $_POST['username']);
self::openIdAuthentication($openid_url, !empty($_POST['remember'])); /** @var Authentication $authentication */
$authentication = self::getClass(Authentication::class);
$authentication->withOpenId($openid_url, !empty($_POST['remember']));
} }
if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') { if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
self::passwordAuthentication( /** @var Authentication $authentication */
$authentication = self::getClass(Authentication::class);
$authentication->withPassword(
self::getApp(),
trim($_POST['username']), trim($_POST['username']),
trim($_POST['password']), trim($_POST['password']),
!empty($_POST['remember']), !empty($_POST['remember'])
$openid_identity,
$openid_server
); );
} }
} }
/**
* Attempts to authenticate using OpenId
*
* @param string $openid_url OpenID URL string
* @param bool $remember Whether to set the session remember flag
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function openIdAuthentication($openid_url, $remember)
{
$noid = Config::get('system', 'no_openid');
$a = self::getApp();
// if it's an email address or doesn't resolve to a URL, fail.
if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
notice(L10n::t('Login failed.') . EOL);
$a->internalRedirect();
// NOTREACHED
}
// Otherwise it's probably an openid.
try {
$openid = new LightOpenID($a->getHostName());
$openid->identity = $openid_url;
Session::set('openid', $openid_url);
Session::set('remember', $remember);
$openid->returnUrl = $a->getBaseURL(true) . '/openid';
$openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
System::externalRedirect($openid->authUrl());
} catch (Exception $e) {
notice(L10n::t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '<br /><br >' . L10n::t('The error message was:') . ' ' . $e->getMessage());
}
}
/**
* Attempts to authenticate using login/password
*
* @param string $username User name
* @param string $password Clear password
* @param bool $remember Whether to set the session remember flag
* @param string $openid_identity OpenID identity
* @param string $openid_server OpenID URL
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function passwordAuthentication($username, $password, $remember, $openid_identity, $openid_server)
{
$record = null;
$addon_auth = [
'username' => $username,
'password' => $password,
'authenticated' => 0,
'user_record' => null
];
$a = self::getApp();
/*
* An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
* Addons should never set 'authenticated' except to indicate success - as hooks may be chained
* and later addons should not interfere with an earlier one that succeeded.
*/
Hook::callAll('authenticate', $addon_auth);
try {
if ($addon_auth['authenticated']) {
$record = $addon_auth['user_record'];
if (empty($record)) {
throw new Exception(L10n::t('Login failed.'));
}
} else {
$record = DBA::selectFirst(
'user',
[],
['uid' => User::getIdFromPasswordAuthentication($username, $password)]
);
}
} catch (Exception $e) {
Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
info('Login failed. Please check your credentials.' . EOL);
$a->internalRedirect();
}
if (!$remember) {
Authentication::setCookie(0); // 0 means delete on browser exit
}
// if we haven't failed up this point, log them in.
Session::set('remember', $remember);
Session::set('last_login_date', DateTimeFormat::utcNow());
if (!empty($openid_identity) || !empty($openid_server)) {
DBA::update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
}
Session::setAuthenticatedForUser($a, $record, true, true);
$return_path = Session::get('return_path', '');
Session::remove('return_path');
$a->internalRedirect($return_path);
}
/**
* @brief Tries to auth the user from the cookie or session
*
* @todo Should be moved to Friendica\Core\Session when it's created
*/
public static function sessionAuth()
{
$a = self::getApp();
// When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
if (isset($_COOKIE["Friendica"])) {
$data = json_decode($_COOKIE["Friendica"]);
if (isset($data->uid)) {
$user = DBA::selectFirst(
'user',
[],
[
'uid' => $data->uid,
'blocked' => false,
'account_expired' => false,
'account_removed' => false,
'verified' => true,
]
);
if (DBA::isResult($user)) {
if (!hash_equals(
Authentication::getCookieHashForUser($user),
$data->hash
)) {
Logger::log("Hash for user " . $data->uid . " doesn't fit.");
Authentication::deleteSession();
$a->internalRedirect();
}
// Renew the cookie
// Expires after 7 days by default,
// can be set via system.auth_cookie_lifetime
$authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
// Do the authentification if not done by now
if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
Session::setAuthenticatedForUser($a, $user);
if (Config::get('system', 'paranoia')) {
$_SESSION['addr'] = $data->ip;
}
}
}
}
}
if (!empty($_SESSION['authenticated'])) {
if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
$contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
if (DBA::isResult($contact)) {
self::getApp()->contact = $contact;
}
}
if (!empty($_SESSION['uid'])) {
// already logged in user returning
$check = Config::get('system', 'paranoia');
// extra paranoia - if the IP changed, log them out
if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
$_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
Authentication::deleteSession();
$a->internalRedirect();
}
$user = DBA::selectFirst(
'user',
[],
[
'uid' => $_SESSION['uid'],
'blocked' => false,
'account_expired' => false,
'account_removed' => false,
'verified' => true,
]
);
if (!DBA::isResult($user)) {
Authentication::deleteSession();
$a->internalRedirect();
}
// Make sure to refresh the last login time for the user if the user
// stays logged in for a long time, e.g. with "Remember Me"
$login_refresh = false;
if (empty($_SESSION['last_login_date'])) {
$_SESSION['last_login_date'] = DateTimeFormat::utcNow();
}
if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
$_SESSION['last_login_date'] = DateTimeFormat::utcNow();
$login_refresh = true;
}
Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
}
}
}
/** /**
* @brief Wrapper for adding a login box. * @brief Wrapper for adding a login box.
* *

View file

@ -6,10 +6,11 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\Authentication; use Friendica\App\Authentication;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Session;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Model\Profile; use Friendica\Model\Profile;
@ -32,7 +33,7 @@ class Logout extends BaseModule
} }
Hook::callAll("logging_out"); Hook::callAll("logging_out");
Authentication::deleteSession(); Session::clear();
if ($visitor_home) { if ($visitor_home) {
System::externalRedirect($visitor_home); System::externalRedirect($visitor_home);

View file

@ -3,6 +3,7 @@
namespace Friendica\Module\TwoFactor; namespace Friendica\Module\TwoFactor;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\App\Authentication;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Session; use Friendica\Core\Session;
@ -41,7 +42,9 @@ class Recovery extends BaseModule
notice(L10n::t('Remaining recovery codes: %d', RecoveryCode::countValidForUser(local_user()))); notice(L10n::t('Remaining recovery codes: %d', RecoveryCode::countValidForUser(local_user())));
// Resume normal login workflow // Resume normal login workflow
Session::setAuthenticatedForUser($a, $a->user, true, true); /** @var Authentication $authentication */
$authentication = self::getClass(Authentication::class);
$authentication->setForUser($a, $a->user, true, true);
} else { } else {
notice(L10n::t('Invalid code, please retry.')); notice(L10n::t('Invalid code, please retry.'));
} }

View file

@ -3,6 +3,7 @@
namespace Friendica\Module\TwoFactor; namespace Friendica\Module\TwoFactor;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\App\Authentication;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
@ -38,7 +39,9 @@ class Verify extends BaseModule
Session::set('2fa', $code); Session::set('2fa', $code);
// Resume normal login workflow // Resume normal login workflow
Session::setAuthenticatedForUser($a, $a->user, true, true); /** @var Authentication $authentication */
$authentication = self::getClass(Authentication::class);
$authentication->setForUser($a, $a->user, true, true);
} else { } else {
self::$errors[] = L10n::t('Invalid code, please retry.'); self::$errors[] = L10n::t('Invalid code, please retry.');
} }

View file

@ -5,6 +5,7 @@
namespace Friendica\Network; namespace Friendica\Network;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\App\Authentication;
use Friendica\Core\Logger; use Friendica\Core\Logger;
use Friendica\Core\Session; use Friendica\Core\Session;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -45,6 +46,8 @@ class FKOAuth1 extends OAuthServer
die('This api requires login'); die('This api requires login');
} }
Session::setAuthenticatedForUser($a, $record, true); /** @var Authentication $authentication */
$authentication = BaseObject::getClass(Authentication::class);
$authentication->setForUser($a, $record, true);
} }
} }

View file

@ -6,6 +6,7 @@ use Friendica\Core\Cache;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n\L10n; use Friendica\Core\L10n\L10n;
use Friendica\Core\Lock\ILock; use Friendica\Core\Lock\ILock;
use Friendica\Core\Session\ISession;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Factory; use Friendica\Factory;
use Friendica\Util; use Friendica\Util;
@ -179,4 +180,11 @@ return [
$_SERVER, $_GET $_SERVER, $_GET
], ],
], ],
ISession::class => [
'instanceOf' => Factory\SessionFactory::class,
'call' => [
['createSession', [$_SERVER], Dice::CHAIN_CALL],
['start', [], Dice::CHAIN_CALL],
],
],
]; ];

View file

@ -0,0 +1,28 @@
<?php
namespace Friendica\Test\Util;
use Friendica\Model\User\Cookie;
/**
* Overrides the Cookie class so all cookie information will be saved to a static public variable
*/
class StaticCookie extends Cookie
{
/** @var array static Cookie array mock */
public static $_COOKIE = [];
/** @var int The last expire time set */
public static $_EXPIRE;
protected function setCookie(string $name, string $value = null, int $expire = null, bool $secure = null)
{
self::$_COOKIE[$name] = $value;
self::$_EXPIRE = $expire;
}
public static function clearStatic()
{
self::$_EXPIRE = null;
self::$_COOKIE = [];
}
}

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']);

View file

@ -11,6 +11,8 @@ use Friendica\BaseObject;
use Friendica\Core\Config\Configuration; use Friendica\Core\Config\Configuration;
use Friendica\Core\Config\PConfiguration; use Friendica\Core\Config\PConfiguration;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Session;
use Friendica\Core\Session\ISession;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
@ -59,7 +61,8 @@ class ApiTest extends DatabaseTest
$this->dice = (new Dice()) $this->dice = (new Dice())
->addRules(include __DIR__ . '/../../static/dependencies.config.php') ->addRules(include __DIR__ . '/../../static/dependencies.config.php')
->addRule(Database::class, ['instanceOf' => StaticDatabase::class, 'shared' => true]); ->addRule(Database::class, ['instanceOf' => StaticDatabase::class, 'shared' => true])
->addRule(ISession::class, ['instanceOf' => Session\Memory::class, 'shared' => true, 'call' => null]);
BaseObject::setDependencyInjection($this->dice); BaseObject::setDependencyInjection($this->dice);
/** @var Database $dba */ /** @var Database $dba */
@ -111,6 +114,10 @@ class ApiTest extends DatabaseTest
// User ID that we know is not in the database // User ID that we know is not in the database
$this->wrongUserId = 666; $this->wrongUserId = 666;
/** @var ISession $session */
$session = BaseObject::getClass(ISession::class);
$session->start();
// Most API require login so we force the session // Most API require login so we force the session
$_SESSION = [ $_SESSION = [
'allow_api' => true, 'allow_api' => true,

View file

@ -0,0 +1,312 @@
<?php
namespace Friendica\Testsrc\Model\User;
use Friendica\App\BaseURL;
use Friendica\Core\Config\Configuration;
use Friendica\Model\User\Cookie;
use Friendica\Test\DatabaseTest;
use Friendica\Test\Util\StaticCookie;
use Mockery\MockInterface;
class CookieTest extends DatabaseTest
{
/** @var MockInterface|Configuration */
private $config;
/** @var MockInterface|BaseURL */
private $baseUrl;
protected function setUp()
{
StaticCookie::clearStatic();
parent::setUp();
$this->config = \Mockery::mock(Configuration::class);
$this->baseUrl = \Mockery::mock(BaseURL::class);
}
protected function tearDown()
{
StaticCookie::clearStatic();
}
/**
* Test if we can create a basic cookie instance
*/
public function testInstance()
{
$this->baseUrl->shouldReceive('getSSLPolicy')->andReturn(true)->once();
$this->config->shouldReceive('get')->with('system', 'site_prvkey')->andReturn('1235')->once();
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn('7')->once();
$cookie = new Cookie($this->config, $this->baseUrl);
$this->assertInstanceOf(Cookie::class, $cookie);
}
public function dataGet()
{
return [
'default' => [
'cookieData' => [
Cookie::NAME => json_encode([
'uid' => -1,
'hash' => 12345,
'ip' => '127.0.0.1',
])
],
'hasValues' => true,
'uid' => -1,
'hash' => 12345,
'ip' => '127.0.0.1',
],
'missing' => [
'cookieData' => [
],
'hasValues' => false,
'uid' => null,
'hash' => null,
'ip' => null,
],
'invalid' => [
'cookieData' => [
Cookie::NAME => 'test',
],
'hasValues' => false,
'uid' => null,
'hash' => null,
'ip' => null,
],
'incomplete' => [
'cookieData' => [
Cookie::NAME => json_encode([
'uid' => -1,
'hash' => 12345,
])
],
'hasValues' => true,
'uid' => -1,
'hash' => 12345,
'ip' => null,
],
];
}
/**
* Test the get() method of the cookie class
*
* @dataProvider dataGet
*/
public function testGet(array $cookieData, bool $hasValues, $uid, $hash, $ip)
{
$this->baseUrl->shouldReceive('getSSLPolicy')->andReturn(true)->once();
$this->config->shouldReceive('get')->with('system', 'site_prvkey')->andReturn('1235')->once();
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn('7')->once();
$cookie = new Cookie($this->config, $this->baseUrl, [], $cookieData);
$this->assertInstanceOf(Cookie::class, $cookie);
$assertData = $cookie->getData();
if (!$hasValues) {
$this->assertEmpty($assertData);
} else {
$this->assertNotEmpty($assertData);
if (isset($uid)) {
$this->assertObjectHasAttribute('uid', $assertData);
$this->assertEquals($uid, $assertData->uid);
} else {
$this->assertObjectNotHasAttribute('uid', $assertData);
}
if (isset($hash)) {
$this->assertObjectHasAttribute('hash', $assertData);
$this->assertEquals($hash, $assertData->hash);
} else {
$this->assertObjectNotHasAttribute('hash', $assertData);
}
if (isset($ip)) {
$this->assertObjectHasAttribute('ip', $assertData);
$this->assertEquals($ip, $assertData->ip);
} else {
$this->assertObjectNotHasAttribute('ip', $assertData);
}
}
}
public function dataCheck()
{
return [
'default' => [
'serverPrivateKey' => 'serverkey',
'userPrivateKey' => 'userkey',
'password' => 'test',
'assertHash' => 'e9b4eb16275a2907b5659d22905b248221d0517dde4a9d5c320b8fe051b1267b',
'assertTrue' => true,
],
'emptyUser' => [
'serverPrivateKey' => 'serverkey',
'userPrivateKey' => '',
'password' => '',
'assertHash' => '',
'assertTrue' => false,
],
'invalid' => [
'serverPrivateKey' => 'serverkey',
'userPrivateKey' => 'bla',
'password' => 'nope',
'assertHash' => 'real wrong!',
'assertTrue' => false,
]
];
}
/**
* Test the check() method of the cookie class
*
* @dataProvider dataCheck
*/
public function testCheck(string $serverPrivateKey, string $userPrivateKey, string $password, string $assertHash, bool $assertTrue)
{
$this->baseUrl->shouldReceive('getSSLPolicy')->andReturn(true)->once();
$this->config->shouldReceive('get')->with('system', 'site_prvkey')->andReturn($serverPrivateKey)->once();
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn('7')->once();
$cookie = new Cookie($this->config, $this->baseUrl);
$this->assertInstanceOf(Cookie::class, $cookie);
$this->assertEquals($assertTrue, $cookie->check($assertHash, $password, $userPrivateKey));
}
public function dataSet()
{
return [
'default' => [
'serverKey' => 23,
'uid' => 0,
'password' => '234',
'privateKey' => '124',
'assertHash' => 'b657a15cfe7ed1f7289c9aa51af14a9a26c966f4ddd74e495fba103d8e872a39',
'remoteIp' => '0.0.0.0',
'serverArray' => [],
'lifetime' => null,
],
'withServerArray' => [
'serverKey' => 23,
'uid' => 0,
'password' => '234',
'privateKey' => '124',
'assertHash' => 'b657a15cfe7ed1f7289c9aa51af14a9a26c966f4ddd74e495fba103d8e872a39',
'remoteIp' => '1.2.3.4',
'serverArray' => ['REMOTE_ADDR' => '1.2.3.4',],
'lifetime' => null,
],
'withLifetime0' => [
'serverKey' => 23,
'uid' => 0,
'password' => '234',
'privateKey' => '124',
'assertHash' => 'b657a15cfe7ed1f7289c9aa51af14a9a26c966f4ddd74e495fba103d8e872a39',
'remoteIp' => '1.2.3.4',
'serverArray' => ['REMOTE_ADDR' => '1.2.3.4',],
'lifetime' => 0,
],
'withLifetime' => [
'serverKey' => 23,
'uid' => 0,
'password' => '234',
'privateKey' => '124',
'assertHash' => 'b657a15cfe7ed1f7289c9aa51af14a9a26c966f4ddd74e495fba103d8e872a39',
'remoteIp' => '1.2.3.4',
'serverArray' => ['REMOTE_ADDR' => '1.2.3.4',],
'lifetime' => 2 * 24 * 60 * 60,
],
];
}
public function assertCookie($uid, $hash, $remoteIp, $lifetime)
{
$this->assertArrayHasKey(Cookie::NAME, StaticCookie::$_COOKIE);
$data = json_decode(StaticCookie::$_COOKIE[Cookie::NAME]);
$this->assertObjectHasAttribute('uid', $data);
$this->assertEquals($uid, $data->uid);
$this->assertObjectHasAttribute('hash', $data);
$this->assertEquals($hash, $data->hash);
$this->assertObjectHasAttribute('ip', $data);
$this->assertEquals($remoteIp, $data->ip);
if (isset($lifetime) && $lifetime !== 0) {
$this->assertLessThanOrEqual(time() + $lifetime, StaticCookie::$_EXPIRE);
} else {
$this->assertLessThanOrEqual(time() + Cookie::DEFAULT_EXPIRE * 24 * 60 * 60, StaticCookie::$_EXPIRE);
}
}
/**
* Test the set() method of the cookie class
*
* @dataProvider dataSet
*/
public function testSet($serverKey, $uid, $password, $privateKey, $assertHash, $remoteIp, $serverArray, $lifetime)
{
$this->baseUrl->shouldReceive('getSSLPolicy')->andReturn(true)->once();
$this->config->shouldReceive('get')->with('system', 'site_prvkey')->andReturn($serverKey)->once();
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn(Cookie::DEFAULT_EXPIRE)->once();
$cookie = new StaticCookie($this->config, $this->baseUrl, $serverArray);
$this->assertInstanceOf(Cookie::class, $cookie);
$cookie->set($uid, $password, $privateKey, $lifetime);
$this->assertCookie($uid, $assertHash, $remoteIp, $lifetime);
}
/**
* Test two different set() of the cookie class (first set is invalid)
*
* @dataProvider dataSet
*/
public function testDoubleSet($serverKey, $uid, $password, $privateKey, $assertHash, $remoteIp, $serverArray, $lifetime)
{
$this->baseUrl->shouldReceive('getSSLPolicy')->andReturn(true)->once();
$this->config->shouldReceive('get')->with('system', 'site_prvkey')->andReturn($serverKey)->once();
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn(Cookie::DEFAULT_EXPIRE)->once();
$cookie = new StaticCookie($this->config, $this->baseUrl, $serverArray);
$this->assertInstanceOf(Cookie::class, $cookie);
// Invalid set, should get overwritten
$cookie->set(-1, 'invalid', 'nothing', -234);
$cookie->set($uid, $password, $privateKey, $lifetime);
$this->assertCookie($uid, $assertHash, $remoteIp, $lifetime);
}
/**
* Test the clear() method of the cookie class
*/
public function testClear()
{
StaticCookie::$_COOKIE = [
Cookie::NAME => 'test'
];
$this->baseUrl->shouldReceive('getSSLPolicy')->andReturn(true)->once();
$this->config->shouldReceive('get')->with('system', 'site_prvkey')->andReturn(24)->once();
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn(Cookie::DEFAULT_EXPIRE)->once();
$cookie = new StaticCookie($this->config, $this->baseUrl);
$this->assertInstanceOf(Cookie::class, $cookie);
$this->assertEquals('test', StaticCookie::$_COOKIE[Cookie::NAME]);
$this->assertEquals(null, StaticCookie::$_EXPIRE);
$cookie->clear();
$this->assertEmpty(StaticCookie::$_COOKIE[Cookie::NAME]);
$this->assertEquals(-3600, StaticCookie::$_EXPIRE);
}
}

File diff suppressed because it is too large Load diff