use Friendica\Content\Feature;
use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\HTML;
-use Friendica\Core\Authentication;
+use Friendica\App\Authentication;
use Friendica\Core\Config;
use Friendica\Core\Hook;
use Friendica\Core\L10n;
$dice->create(\Friendica\App\Module::class),
$dice->create(\Friendica\App\Router::class),
$dice->create(\Friendica\Core\Config\PConfiguration::class),
- $dice->create(\Friendica\Core\Authentication::class)
+ $dice->create(\Friendica\App\Authentication::class)
);
use Friendica\App;
use Friendica\BaseObject;
-use Friendica\Core\Authentication;
+use Friendica\App\Authentication;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\Logger;
{
/** @var Authentication $authentication */
$authentication = BaseObject::getClass(Authentication::class);
- $authentication->withSession($a, $_COOKIE);
+ $authentication->withSession($a);
$dfrn_id = $_GET['dfrn_id'] ?? '';
$type = ($_GET['type'] ?? '') ?: 'data';
use Friendica\App;
use Friendica\BaseObject;
-use Friendica\Core\Authentication;
+use Friendica\App\Authentication;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\App\Arguments;
use Friendica\App\BaseURL;
use Friendica\App\Page;
-use Friendica\Core\Authentication;
+use Friendica\App\Authentication;
use Friendica\Core\Config\Cache\ConfigCache;
use Friendica\Core\Config\Configuration;
use Friendica\Core\Config\PConfiguration;
Model\Profile::openWebAuthInit($token);
}
- $auth->withSession($this, $_COOKIE);
+ $auth->withSession($this);
if (empty($_SESSION['authenticated'])) {
header('X-Account-Management-Status: none');
--- /dev/null
+<?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;
+
+ /**
+ * Authentication constructor.
+ *
+ * @param Configuration $config
+ * @param App\BaseURL $baseUrl
+ * @param L10n $l10n
+ * @param Database $dba
+ * @param LoggerInterface $logger
+ * @param User\Cookie $cookie
+ */
+ public function __construct(Configuration $config, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie)
+ {
+ $this->config = $config;
+ $this->baseUrl = $baseUrl;
+ $this->l10n = $l10n;
+ $this->dba = $dba;
+ $this->logger = $logger;
+ $this->cookie = $cookie;
+ }
+
+ /**
+ * @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) && isset($data->uid)) {
+
+ $user = $this->dba->selectFirst(
+ 'user',
+ [],
+ [
+ 'uid' => $data->uid,
+ 'blocked' => false,
+ 'account_expired' => false,
+ 'account_removed' => false,
+ 'verified' => true,
+ ]
+ );
+ if (DBA::isResult($user)) {
+ if (!$this->cookie->check($data->hash,
+ $user['password'] ?? '',
+ $user['prvKey'] ?? '')) {
+ $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
+ 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 (!Session::get('authenticated')) {
+ $this->setForUser($a, $user);
+
+ if ($this->config->get('system', 'paranoia')) {
+ Session::set('addr', $data->ip);
+ }
+ }
+ }
+ }
+
+ if (Session::get('authenticated')) {
+ if (Session::get('visitor_id') && !Session::get('uid')) {
+ $contact = $this->dba->selectFirst('contact', [], ['id' => Session::get('visitor_id')]);
+ if ($this->dba->isResult($contact)) {
+ $a->contact = $contact;
+ }
+ }
+
+ if (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 && (Session::get('addr') != $_SERVER['REMOTE_ADDR'])) {
+ $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
+ 'addr' => Session::get('addr'),
+ 'remote_addr' => $_SERVER['REMOTE_ADDR']]
+ );
+ Session::delete();
+ $this->baseUrl->redirect();
+ }
+
+ $user = $this->dba->selectFirst(
+ 'user',
+ [],
+ [
+ 'uid' => Session::get('uid'),
+ 'blocked' => false,
+ 'account_expired' => false,
+ 'account_removed' => false,
+ 'verified' => true,
+ ]
+ );
+ if (!$this->dba->isResult($user)) {
+ 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 (!Session::get('last_login_date')) {
+ Session::set('last_login_date', DateTimeFormat::utcNow());
+ }
+ if (strcmp(DateTimeFormat::utc('now - 12 hours'), Session::get('last_login_date')) > 0) {
+ 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;
+ Session::set('openid', $openid_url);
+ 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.
+ Session::set('remember', $remember);
+ Session::set('last_login_date', DateTimeFormat::utcNow());
+
+ $openid_identity = Session::get('openid_identity');
+ $openid_server = 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 = Session::get('return_path', '');
+ 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)
+ {
+ 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']);
+ 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 (Session::get('submanage')) {
+ $user = $this->dba->selectFirst('user', ['uid'], ['uid' => 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'];
+ 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 (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']);
+ 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' && Session::exists('return_path')) {
+ $this->baseUrl->redirect(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 (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');
+ }
+ }
+}
+++ /dev/null
-<?php
-
-/**
- * @file /src/Core/Authentication.php
- */
-
-namespace Friendica\Core;
-
-use Exception;
-use Friendica\App;
-use Friendica\Core\Config\Configuration;
-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;
-
- /**
- * Authentication constructor.
- *
- * @param Configuration $config
- * @param App\BaseURL $baseUrl
- * @param L10n $l10n
- * @param Database $dba
- * @param LoggerInterface $logger
- */
- public function __construct(Configuration $config, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger)
- {
- $this->config = $config;
- $this->baseUrl = $baseUrl;
- $this->l10n = $l10n;
- $this->dba = $dba;
- $this->logger = $logger;
- }
-
- /**
- * @brief Tries to auth the user from the cookie or session
- *
- * @param App $a The Friendica Application context
- * @param array $cookie The $_COOKIE array
- *
- * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
- * @throws Exception In case of general exceptions (like SQL Grammar)
- */
- public function withSession(App $a, array $cookie)
- {
- // 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 = $this->dba->selectFirst(
- 'user',
- [],
- [
- 'uid' => $data->uid,
- 'blocked' => false,
- 'account_expired' => false,
- 'account_removed' => false,
- 'verified' => true,
- ]
- );
- if (DBA::isResult($user)) {
- if (!Session::checkCookie($data->hash, $user)) {
- $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
- Session::delete();
- $this->baseUrl->redirect();
- }
-
- // Renew the cookie
- // Expires after 7 days by default,
- // can be set via system.auth_cookie_lifetime
- $authcookiedays = $this->config->get('system', 'auth_cookie_lifetime', 7);
- Session::setCookie($authcookiedays * 24 * 60 * 60, $user);
-
- // Do the authentification if not done by now
- if (!Session::get('authenticated')) {
- $this->setForUser($a, $user);
-
- if ($this->config->get('system', 'paranoia')) {
- Session::set('addr', $data->ip);
- }
- }
- }
- }
- }
-
- if (Session::get('authenticated')) {
- if (Session::get('visitor_id') && !Session::get('uid')) {
- $contact = $this->dba->selectFirst('contact', [], ['id' => Session::get('visitor_id')]);
- if ($this->dba->isResult($contact)) {
- $a->contact = $contact;
- }
- }
-
- if (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 && (Session::get('addr') != $_SERVER['REMOTE_ADDR'])) {
- $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
- 'addr' => Session::get('addr'),
- 'remote_addr' => $_SERVER['REMOTE_ADDR']]
- );
- Session::delete();
- $this->baseUrl->redirect();
- }
-
- $user = $this->dba->selectFirst(
- 'user',
- [],
- [
- 'uid' => Session::get('uid'),
- 'blocked' => false,
- 'account_expired' => false,
- 'account_removed' => false,
- 'verified' => true,
- ]
- );
- if (!$this->dba->isResult($user)) {
- 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 (!Session::get('last_login_date')) {
- Session::set('last_login_date', DateTimeFormat::utcNow());
- }
- if (strcmp(DateTimeFormat::utc('now - 12 hours'), Session::get('last_login_date')) > 0) {
- 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;
- Session::set('openid', $openid_url);
- 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) {
- Session::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());
-
- $openid_identity = Session::get('openid_identity');
- $openid_server = 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 = Session::get('return_path', '');
- 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)
- {
- 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']);
- 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 (Session::get('submanage')) {
- $user = $this->dba->selectFirst('user', ['uid'], ['uid' => 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'];
- 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 (Session::get('remember')) {
- $a->getLogger()->info('Injecting cookie for remembered user ' . $user_record['nickname']);
- Session::setCookie(604800, $user_record);
- 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' && Session::exists('return_path')) {
- $this->baseUrl->redirect(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 (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');
- }
- }
-}
namespace Friendica\Core;
use Friendica\App;
+use Friendica\BaseObject;
use Friendica\Core\Session\CacheSessionHandler;
use Friendica\Core\Session\DatabaseSessionHandler;
use Friendica\Database\DBA;
use Friendica\Model\Contact;
+use Friendica\Model\User;
use Friendica\Util\Strings;
/**
return $_SESSION['authenticated'];
}
- /**
- * @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
- */
- private 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 Checks if the "Friendica" cookie is set
- *
- * @param string $hash
- * @param array $user Record from "user" table
- *
- * @return boolean True, if the cookie is set
- *
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
- public static function checkCookie(string $hash, array $user)
- {
- return hash_equals(
- self::getCookieHashForUser($user),
- $hash
- );
- }
-
/**
* @brief Kills the "Friendica" cookie and all session data
*/
public static function delete()
{
- self::setCookie(-3600); // make sure cookie is deleted on browser close, as a security measure
+ /** @var User\Cookie $cookie */
+ $cookie = BaseObject::getClass(User\Cookie::class);
+ $cookie->clear();
+ $_SESSION = [];
session_unset();
session_destroy();
}
use DivineOmega\PasswordExposed;
use Exception;
+use Friendica\App;
use Friendica\Core\Config;
use Friendica\Core\Hook;
use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig;
use Friendica\Core\Protocol;
+use Friendica\Core\Session;
use Friendica\Core\System;
use Friendica\Core\Worker;
use Friendica\Database\DBA;
--- /dev/null
+<?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 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, array $server = [], array $cookie = [])
+ {
+ if (!empty($server['REMOTE_ADDR'])) {
+ $this->remoteAddr = $server['REMOTE_ADDR'];
+ }
+
+ $this->sslEnabled = $config->get('system', 'ssl_policy') === 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;
+ } 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, true);
+ }
+
+ /**
+ * 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, true);
+ }
+
+ /**
+ * 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 string $path [optional]
+ * @param string $domain [optional]
+ * @param bool $secure [optional]
+ * @param bool $httponly [optional] <p>
+ *
+ * @return bool If output exists prior to calling this function,
+ *
+ * @since 4.0
+ * @since 5.0
+ */
+ protected function setCookie(string $name, string $value = null, int $expire = null,
+ string $path = null, string $domain = null,
+ bool $secure = null, bool $httponly = null)
+ {
+ return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
+ }
+}
namespace Friendica\Module;
use Friendica\BaseModule;
-use Friendica\Core\Authentication;
+use Friendica\App\Authentication;
use Friendica\Core\Hook;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
namespace Friendica\Module;
use Friendica\BaseModule;
-use Friendica\Core\Authentication;
+use Friendica\App\Authentication;
use Friendica\Core\Config;
use Friendica\Core\Hook;
use Friendica\Core\L10n;
namespace Friendica\Module;
use Friendica\BaseModule;
-use Friendica\Core\Authentication;
+use Friendica\App\Authentication;
use Friendica\Core\Cache;
use Friendica\Core\Hook;
use Friendica\Core\L10n;
namespace Friendica\Module\TwoFactor;
use Friendica\BaseModule;
-use Friendica\Core\Authentication;
+use Friendica\App\Authentication;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\Core\Session;
namespace Friendica\Module\TwoFactor;
use Friendica\BaseModule;
-use Friendica\Core\Authentication;
+use Friendica\App\Authentication;
use Friendica\Core\L10n;
use Friendica\Core\PConfig;
use Friendica\Core\Renderer;
namespace Friendica\Network;
use Friendica\BaseObject;
-use Friendica\Core\Authentication;
+use Friendica\App\Authentication;
use Friendica\Core\Logger;
use Friendica\Core\Session;
use Friendica\Database\DBA;
--- /dev/null
+<?php
+
+namespace Friendica\Testsrc\Model\User;
+
+use Friendica\Core\Config\Configuration;
+use Friendica\Model\User\Cookie;
+use Friendica\Test\DatabaseTest;
+use Mockery\MockInterface;
+
+class CookieTest extends DatabaseTest
+{
+ /** @var MockInterface|Configuration */
+ private $config;
+
+ protected function setUp()
+ {
+ parent::setUp();;
+
+ $this->config = \Mockery::mock(Configuration::class);
+ }
+
+ public function testInstance()
+ {
+ $this->config->shouldReceive('get')->with('system', 'ssl_policy')->andReturn(1)->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->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,
+ ],
+ ];
+ }
+
+ /**
+ * @dataProvider dataGet
+ */
+ public function testGet(array $cookieData, bool $hasValues, $uid, $hash, $ip)
+ {
+ $this->config->shouldReceive('get')->with('system', 'ssl_policy')->andReturn(1)->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, [], $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,
+ ]
+ ];
+ }
+
+ /**
+ * @dataProvider dataCheck
+ */
+ public function testCheck(string $serverPrivateKey, string $userPrivateKey, string $password, string $assertHash, bool $assertTrue)
+ {
+ $this->config->shouldReceive('get')->with('system', 'ssl_policy')->andReturn(1)->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->assertInstanceOf(Cookie::class, $cookie);
+
+ $this->assertEquals($assertTrue, $cookie->check($assertHash, $password, $userPrivateKey));
+ }
+
+ public function testSet()
+ {
+ $this->markTestIncomplete('Needs mocking of setcookie() first.');
+ }
+
+ public function testClear()
+ {
+ $this->markTestIncomplete('Needs mocking of setcookie() first.');
+ }
+}