]> git.mxchange.org Git - friendica.git/commitdiff
Refactor "Authentication" class with four main methods:
authornupplaPhil <admin@philipp.info>
Tue, 3 Dec 2019 21:29:37 +0000 (22:29 +0100)
committernupplaPhil <admin@philipp.info>
Thu, 5 Dec 2019 22:02:51 +0000 (23:02 +0100)
- withSession() - for auto authentication with Session/Cookie variables
- withOpenId() - for authentication with an OpenID account
- withPassword() - for authentication with Password
- setForUser() - for setting the user auth context of the current session

Refactor "Session" class - contains now "native" Session Management methods

13 files changed:
include/api.php
index.php
mod/dfrn_poll.php
mod/openid.php
src/App.php
src/Core/Authentication.php
src/Core/Session.php
src/Module/Delegation.php
src/Module/Login.php
src/Module/Logout.php
src/Module/TwoFactor/Recovery.php
src/Module/TwoFactor/Verify.php
src/Network/FKOAuth1.php

index 681515cc376cc0a9bfeb11bad6ad05521b972cb4..f4b95733e97132e4109b9d5133b8e08cec32ecb2 100644 (file)
@@ -12,6 +12,7 @@ use Friendica\Content\ContactSelector;
 use Friendica\Content\Feature;
 use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\HTML;
+use Friendica\Core\Authentication;
 use Friendica\Core\Config;
 use Friendica\Core\Hook;
 use Friendica\Core\L10n;
@@ -253,7 +254,9 @@ function api_login(App $a)
                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;
 
index 5407532d494fdec91eefcf52b00c966ba8c26056..00ec0edb75e5d25e7de69d5ea42ba2b37a392678 100644 (file)
--- a/index.php
+++ b/index.php
@@ -22,5 +22,6 @@ $a = \Friendica\BaseObject::getApp();
 $a->runFrontend(
        $dice->create(\Friendica\App\Module::class),
        $dice->create(\Friendica\App\Router::class),
-       $dice->create(\Friendica\Core\Config\PConfiguration::class)
+       $dice->create(\Friendica\Core\Config\PConfiguration::class),
+       $dice->create(\Friendica\Core\Authentication::class)
 );
index 6aef31a54635840fd78441f46c167efee94b389c..892aecacb7ec463dce85cbaffc55ec38a606a9f4 100644 (file)
@@ -5,6 +5,7 @@
  */
 
 use Friendica\App;
+use Friendica\BaseObject;
 use Friendica\Core\Authentication;
 use Friendica\Core\Config;
 use Friendica\Core\L10n;
@@ -21,7 +22,9 @@ use Friendica\Util\XML;
 
 function dfrn_poll_init(App $a)
 {
-       Authentication::sessionAuth();
+       /** @var Authentication $authentication */
+       $authentication = BaseObject::getClass(Authentication::class);
+       $authentication->withSession($a, $_COOKIE);
 
        $dfrn_id         =  $_GET['dfrn_id']         ?? '';
        $type            = ($_GET['type']            ?? '') ?: 'data';
index 98748c21d8d7ad9f4861d900754114a0d7ee86b9..0c21f7a31c350ef9382b555d79db92f33e5cdd44 100644 (file)
@@ -4,6 +4,8 @@
  */
 
 use Friendica\App;
+use Friendica\BaseObject;
+use Friendica\Core\Authentication;
 use Friendica\Core\Config;
 use Friendica\Core\L10n;
 use Friendica\Core\Logger;
@@ -45,7 +47,9 @@ function openid_content(App $a) {
 
                                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
                                // and we fell through
index 4d652496bfb7b2dd90b70c3d536a8d121657cb37..243f5ba07586a123c236813a0584ce481cb16b13 100644 (file)
@@ -13,6 +13,7 @@ use Friendica\Core\Config\Cache\ConfigCache;
 use Friendica\Core\Config\Configuration;
 use Friendica\Core\Config\PConfiguration;
 use Friendica\Core\L10n\L10n;
+use Friendica\Core\Session;
 use Friendica\Core\System;
 use Friendica\Core\Theme;
 use Friendica\Database\Database;
@@ -641,10 +642,11 @@ class App
         * @param App\Module     $module The determined module
         * @param App\Router     $router
         * @param PConfiguration $pconfig
+        * @param Authentication $auth The Authentication backend of the node
         * @throws HTTPException\InternalServerErrorException
         * @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();
 
@@ -718,7 +720,7 @@ class App
                                Model\Profile::openWebAuthInit($token);
                        }
 
-                       Authentication::sessionAuth();
+                       $auth->withSession($this, $_COOKIE);
 
                        if (empty($_SESSION['authenticated'])) {
                                header('X-Account-Management-Status: none');
index 6ea727871b62004b244dfc06f311bb59757b7cd1..39de73ce02205e7e1a2e1df34ccfcb86d193fb07 100644 (file)
 
 namespace Friendica\Core;
 
+use Exception;
 use Friendica\App;
-use Friendica\BaseObject;
+use Friendica\Core\Config\Configuration;
+use Friendica\Database\Database;
 use Friendica\Database\DBA;
 use Friendica\Model\User;
-use Friendica\Network\HTTPException\ForbiddenException;
+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 extends BaseObject
+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 \Friendica\Network\HTTPException\InternalServerErrorException
+        *
+        * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
         */
-       public static function openIdAuthentication($openid_url, $remember)
+       public function withOpenId(string $openid_url, bool $remember)
        {
-               $noid = Config::get('system', 'no_openid');
-
-               $a = self::getApp();
+               $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(L10n::t('Login failed.') . EOL);
-                       $a->internalRedirect();
-                       // NOTREACHED
+                       notice($this->l10n->t('Login failed.') . EOL);
+                       $this->baseUrl->redirect();
                }
 
                // Otherwise it's probably an openid.
                try {
-                       $openid = new LightOpenID($a->getHostName());
+                       $openid           = new LightOpenID($this->baseUrl->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'];
+                       $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(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());
+                       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 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
+        * @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 static function passwordAuthentication($username, $password, $remember, $openid_identity, $openid_server)
+       public function withPassword(App $a, string $username, string $password, bool $remember)
        {
                $record = null;
 
                $addon_auth = [
-                       'username' => $username,
-                       'password' => $password,
+                       'username'      => $username,
+                       'password'      => $password,
                        'authenticated' => 0,
-                       'user_record' => null
+                       '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
@@ -89,199 +225,159 @@ class Authentication extends BaseObject
                                $record = $addon_auth['user_record'];
 
                                if (empty($record)) {
-                                       throw new Exception(L10n::t('Login failed.'));
+                                       throw new Exception($this->l10n->t('Login failed.'));
                                }
                        } else {
-                               $record = DBA::selectFirst(
+                               $record = $this->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();
+                       $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) {
-                       Authentication::setCookie(0); // 0 means delete on browser exit
+                       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)) {
-                       DBA::update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
+                       $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
                }
 
-               Session::setAuthenticatedForUser($a, $record, true, true);
+               $this->setForUser($a, $record, true, true);
 
                $return_path = Session::get('return_path', '');
                Session::remove('return_path');
 
-               $a->internalRedirect($return_path);
+               $this->baseUrl->redirect($return_path);
        }
 
        /**
-        * @brief Tries to auth the user from the cookie or session
+        * @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
         *
-        * @todo Should be moved to Friendica\Core\Session when it's created
+        * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
+        * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
         */
-       public static function sessionAuth()
+       public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
        {
-               $a = self::getApp();
+               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'];
+               }
 
-               // 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)) {
+               $masterUid = $user_record['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();
-                                       }
+               if (Session::get('submanage')) {
+                       $user = $this->dba->selectFirst('user', ['uid'], ['uid' => Session::get('submanage')]);
+                       if ($this->dba->isResult($user)) {
+                               $masterUid = $user['uid'];
+                       }
+               }
 
-                                       // 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);
+               $a->identities = User::identities($masterUid);
 
-                                       // Do the authentification if not done by now
-                                       if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
-                                               Session::setAuthenticatedForUser($a, $user);
+               if ($login_initial) {
+                       $this->logger->info('auth_identities: ' . print_r($a->identities, true));
+               }
 
-                                               if (Config::get('system', 'paranoia')) {
-                                                       $_SESSION['addr'] = $data->ip;
-                                               }
-                                       }
-                               }
-                       }
+               if ($login_refresh) {
+                       $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
                }
 
-               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;
-                               }
-                       }
+               $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);
+               }
 
-                       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();
-                               }
+               header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
 
-                               $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();
-                               }
+               if ($login_initial || $login_refresh) {
+                       $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
 
-                               // 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;
-                               }
+                       // Set the login date for all identities of the user
+                       $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
+                               ['parent-uid' => $masterUid, 'account_removed' => false]);
+               }
 
-                               Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
+               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');
                        }
                }
-       }
 
-       /**
-        * @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")
-               );
-       }
+               $this->twoFactorCheck($user_record['uid'], $a);
 
-       /**
-        * @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 ($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']));
+                       }
                }
 
-               if ($user) {
-                       $value = json_encode([
-                               "uid" => $user["uid"],
-                               "hash" => self::getCookieHashForUser($user),
-                               "ip" => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
-                       ]);
-               } else {
-                       $value = "";
-               }
+               $a->user = $user_record;
+
+               if ($login_initial) {
+                       Hook::callAll('logged_in', $a->user);
 
-               setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL), true);
+                       if ($a->module !== 'home' && Session::exists('return_path')) {
+                               $this->baseUrl->redirect(Session::get('return_path'));
+                       }
+               }
        }
 
        /**
-        * @brief Kills the "Friendica" cookie and all session data
+        * @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)
         */
-       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)
+       private function twoFactorCheck(int $uid, App $a)
        {
                // Check user setting, if 2FA disabled return
                if (!PConfig::get($uid, '2fa', 'verified')) {
@@ -300,7 +396,7 @@ class Authentication extends BaseObject
 
                // Case 2: No valid 2FA session: redirect to code verification page
                if ($a->isAjax()) {
-                       throw new ForbiddenException();
+                       throw new HTTPException\ForbiddenException();
                } else {
                        $a->internalRedirect('2fa');
                }
index aaead868a0377cdff2999e7788a63e05c628d292..02e10482d52ba466e6cd5fa27a712c372cfb02e6 100644 (file)
@@ -10,8 +10,6 @@ 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\DateTimeFormat;
 use Friendica\Util\Strings;
 
 /**
@@ -104,117 +102,11 @@ class Session
         */
        public static function clear()
        {
+               session_unset();
+               session_start();
                $_SESSION = [];
        }
 
-       /**
-        * @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'));
-                       }
-               }
-       }
-
        /**
         * Returns contact ID for given user ID
         *
@@ -278,4 +170,75 @@ class Session
 
                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
+               session_unset();
+               session_destroy();
+       }
 }
index d2930317c08ce638aa22b54e10dec3485a33265d..2e3a5cafeaed92178d456db2fe96b0688d173dcf 100644 (file)
@@ -3,6 +3,7 @@
 namespace Friendica\Module;
 
 use Friendica\BaseModule;
+use Friendica\Core\Authentication;
 use Friendica\Core\Hook;
 use Friendica\Core\L10n;
 use Friendica\Core\Renderer;
@@ -79,7 +80,9 @@ class Delegation extends BaseModule
 
                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) {
                        Session::set('submanage', $original_id);
index f43bd221e8b8bb80e6d4ed803c6d959deec71dea..8ecf3e40c8d4950e11e39d078a427257af77aefe 100644 (file)
@@ -35,11 +35,8 @@ class Login extends BaseModule
 
        public static function post(array $parameters = [])
        {
-               $openid_identity = Session::get('openid_identity');
-               $openid_server = Session::get('openid_server');
-
                $return_path = Session::get('return_path');
-               session_unset();
+               Session::clear();
                Session::set('return_path', $return_path);
 
                // OpenId Login
@@ -50,16 +47,19 @@ class Login extends BaseModule
                ) {
                        $openid_url = trim(($_POST['openid_url'] ?? '') ?: $_POST['username']);
 
-                       Authentication::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') {
-                       Authentication::passwordAuthentication(
+                       /** @var Authentication $authentication */
+                       $authentication = self::getClass(Authentication::class);
+                       $authentication->withPassword(
+                               self::getApp(),
                                trim($_POST['username']),
                                trim($_POST['password']),
-                               !empty($_POST['remember']),
-                               $openid_identity,
-                               $openid_server
+                               !empty($_POST['remember'])
                        );
                }
        }
index 49ede01a3d7a1544c32417ff1606ec36a6ff0cdd..877a8cda050d825bec651c1b387e3b626cadad65 100644 (file)
@@ -10,6 +10,7 @@ use Friendica\Core\Authentication;
 use Friendica\Core\Cache;
 use Friendica\Core\Hook;
 use Friendica\Core\L10n;
+use Friendica\Core\Session;
 use Friendica\Core\System;
 use Friendica\Model\Profile;
 
@@ -32,7 +33,7 @@ class Logout extends BaseModule
                }
 
                Hook::callAll("logging_out");
-               Authentication::deleteSession();
+               Session::delete();
 
                if ($visitor_home) {
                        System::externalRedirect($visitor_home);
index bd87836463c7f9df4800868861340a96a3248bc9..f1454469f240f9719e807d17343e208ae6bc8b63 100644 (file)
@@ -3,6 +3,7 @@
 namespace Friendica\Module\TwoFactor;
 
 use Friendica\BaseModule;
+use Friendica\Core\Authentication;
 use Friendica\Core\L10n;
 use Friendica\Core\Renderer;
 use Friendica\Core\Session;
@@ -41,7 +42,9 @@ class Recovery extends BaseModule
                                notice(L10n::t('Remaining recovery codes: %d', RecoveryCode::countValidForUser(local_user())));
 
                                // 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 {
                                notice(L10n::t('Invalid code, please retry.'));
                        }
index 27001683e9e41de0bf460019e8f264b25d2b0dc1..e4a0b2ff186fa2b6af5aefd908a95157353360ac 100644 (file)
@@ -3,6 +3,7 @@
 namespace Friendica\Module\TwoFactor;
 
 use Friendica\BaseModule;
+use Friendica\Core\Authentication;
 use Friendica\Core\L10n;
 use Friendica\Core\PConfig;
 use Friendica\Core\Renderer;
@@ -38,7 +39,9 @@ class Verify extends BaseModule
                                Session::set('2fa', $code);
 
                                // 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 {
                                self::$errors[] = L10n::t('Invalid code, please retry.');
                        }
index eb13290577383f79dc7f058c38cfca2e600fe7d4..81c0c1b2917e1ce10d81064fd30ffa8188b5e33e 100644 (file)
@@ -5,6 +5,7 @@
 namespace Friendica\Network;
 
 use Friendica\BaseObject;
+use Friendica\Core\Authentication;
 use Friendica\Core\Logger;
 use Friendica\Core\Session;
 use Friendica\Database\DBA;
@@ -45,6 +46,8 @@ class FKOAuth1 extends OAuthServer
                        die('This api requires login');
                }
 
-               Session::setAuthenticatedForUser($a, $record, true);
+               /** @var Authentication $authentication */
+               $authentication = BaseObject::getClass(Authentication::class);
+               $authentication->setForUser($a, $record, true);
        }
 }