]> git.mxchange.org Git - friendica.git/blobdiff - src/Security/Authentication.php
"getStyledURL" is now public
[friendica.git] / src / Security / Authentication.php
index ce101477e0a2ee043764ea18b70ac98c8d0ad970..91963ee399d130748b2d48df7277761f0cfe0615 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @copyright Copyright (C) 2010-2021, the Friendica project
+ * @copyright Copyright (C) 2010-2023, the Friendica project
  *
  * @license GNU AGPL version 3 or any later version
  *
@@ -23,10 +23,10 @@ namespace Friendica\Security;
 
 use Exception;
 use Friendica\App;
-use Friendica\Core\Config\IConfig;
-use Friendica\Core\PConfig\IPConfig;
+use Friendica\Core\Config\Capability\IManageConfigValues;
+use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
 use Friendica\Core\Hook;
-use Friendica\Core\Session;
+use Friendica\Core\Session\Capability\IHandleUserSessions;
 use Friendica\Core\System;
 use Friendica\Database\Database;
 use Friendica\Database\DBA;
@@ -36,10 +36,10 @@ use Friendica\Network\HTTPException;
 use Friendica\Security\TwoFactor\Repository\TrustedBrowser;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
-use Friendica\Util\Strings;
 use LightOpenID;
 use Friendica\Core\L10n;
-use Friendica\Core\Logger;
+use Friendica\Core\Worker;
+use Friendica\Model\Contact;
 use Psr\Log\LoggerInterface;
 
 /**
@@ -47,7 +47,7 @@ use Psr\Log\LoggerInterface;
  */
 class Authentication
 {
-       /** @var IConfig */
+       /** @var IManageConfigValues */
        private $config;
        /** @var App\Mode */
        private $mode;
@@ -61,35 +61,51 @@ class Authentication
        private $logger;
        /** @var User\Cookie */
        private $cookie;
-       /** @var Session\ISession */
+       /** @var IHandleUserSessions */
        private $session;
-       /** @var IPConfig */
+       /** @var IManagePersonalConfigValues */
        private $pConfig;
+       /** @var string */
+       private $remoteAddress;
+
+       /**
+        * Sets the X-Account-Management-Status header
+        *
+        * mainly extracted to make it overridable for tests
+        *
+        * @param array $user_record
+        */
+       protected function setXAccMgmtStatusHeader(array $user_record)
+       {
+               header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
+       }
 
        /**
         * Authentication constructor.
         *
-        * @param IConfig          $config
-        * @param App\Mode         $mode
-        * @param App\BaseURL      $baseUrl
-        * @param L10n             $l10n
-        * @param Database         $dba
-        * @param LoggerInterface  $logger
-        * @param User\Cookie      $cookie
-        * @param Session\ISession $session
-        * @param IPConfig         $pConfig
+        * @param IManageConfigValues         $config
+        * @param App\Mode                    $mode
+        * @param App\BaseURL                 $baseUrl
+        * @param L10n                        $l10n
+        * @param Database                    $dba
+        * @param LoggerInterface             $logger
+        * @param User\Cookie                 $cookie
+        * @param IHandleUserSessions         $session
+        * @param IManagePersonalConfigValues $pConfig
+        * @param App\Request                 $request
         */
-       public function __construct(IConfig $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session, IPConfig $pConfig)
+       public function __construct(IManageConfigValues $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, IHandleUserSessions $session, IManagePersonalConfigValues $pConfig, App\Request $request)
        {
-               $this->config  = $config;
-               $this->mode    = $mode;
-               $this->baseUrl = $baseUrl;
-               $this->l10n    = $l10n;
-               $this->dba     = $dba;
-               $this->logger  = $logger;
-               $this->cookie  = $cookie;
-               $this->session = $session;
-               $this->pConfig = $pConfig;
+               $this->config        = $config;
+               $this->mode          = $mode;
+               $this->baseUrl       = $baseUrl;
+               $this->l10n          = $l10n;
+               $this->dba           = $dba;
+               $this->logger        = $logger;
+               $this->cookie        = $cookie;
+               $this->session       = $session;
+               $this->pConfig       = $pConfig;
+               $this->remoteAddress = $request->getRemoteAddress();
        }
 
        /**
@@ -129,7 +145,7 @@ class Authentication
                                // Renew the cookie
                                $this->cookie->send();
 
-                               // Do the authentification if not done by now
+                               // Do the authentication if not done by now
                                if (!$this->session->get('authenticated')) {
                                        $this->setForUser($a, $user);
 
@@ -142,9 +158,9 @@ class Authentication
 
                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')]);
+                               $contact = $this->dba->selectFirst('contact', ['id'], ['id' => $this->session->get('visitor_id')]);
                                if ($this->dba->isResult($contact)) {
-                                       $a->contact = $contact;
+                                       $a->setContactId($contact['id']);
                                }
                        }
 
@@ -152,10 +168,11 @@ class Authentication
                                // 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'])) {
+                               if ($check && ($this->session->get('addr') != $this->remoteAddress)) {
                                        $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
-                                                       'addr'        => $this->session->get('addr'),
-                                                       'remote_addr' => $_SERVER['REMOTE_ADDR']]
+                                               'addr'        => $this->session->get('addr'),
+                                               'remote_addr' => $this->remoteAddress
+                                       ]
                                        );
                                        $this->session->clear();
                                        $this->baseUrl->redirect();
@@ -207,36 +224,40 @@ class Authentication
 
                // 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.'));
+                       DI::sysmsg()->addNotice($this->l10n->t('Login failed.'));
                        $this->baseUrl->redirect();
                }
 
                // Otherwise it's probably an openid.
                try {
-                       $openid           = new LightOpenID($this->baseUrl->getHostname());
+                       $openid           = new LightOpenID($this->baseUrl->getHost());
                        $openid->identity = $openid_url;
                        $this->session->set('openid', $openid_url);
                        $this->session->set('remember', $remember);
-                       $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
+                       $openid->returnUrl = $this->baseUrl . '/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());
+                       DI::sysmsg()->addNotice($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
+        * @param App    $a           The Friendica Application context
+        * @param string $username
+        * @param string $password    Clear password
+        * @param bool   $remember    Whether to set the session remember flag
+        * @param string $return_path The relative path to redirect the user to after authentication
         *
-        * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
-        * @throws Exception A general Exception (like SQL Grammar exceptions)
+        * @throws HTTPException\ForbiddenException
+        * @throws HTTPException\FoundException
+        * @throws HTTPException\InternalServerErrorException In case of Friendica internal exceptions
+        * @throws HTTPException\MovedPermanentlyException
+        * @throws HTTPException\TemporaryRedirectException
         */
-       public function withPassword(App $a, string $username, string $password, bool $remember)
+       public function withPassword(App $a, string $username, string $password, bool $remember, string $return_path = '')
        {
                $record = null;
 
@@ -247,13 +268,17 @@ class Authentication
                                ['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']]);
-                       notice($this->l10n->t('Login failed. Please check your credentials.'));
+                       $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => $username, 'ip' => $this->remoteAddress]);
+                       DI::sysmsg()->addNotice($this->l10n->t('Login failed. Please check your credentials.'));
                        $this->baseUrl->redirect();
                }
 
                if (!$remember) {
+                       $trusted = $this->cookie->get('2fa_cookie_hash') ?? null;
                        $this->cookie->clear();
+                       if ($trusted) {
+                               $this->cookie->set('2fa_cookie_hash', $trusted);
+                       }
                }
 
                // if we haven't failed up this point, log them in.
@@ -267,10 +292,14 @@ class Authentication
                        $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
                }
 
-               $this->setForUser($a, $record, true, true);
+               /**
+                * @see User::getPasswordRegExp()
+                */
+               if (PASSWORD_DEFAULT === PASSWORD_BCRYPT && strlen($password) > 72) {
+                       $return_path = '/security/password_too_long?' . http_build_query(['return_path' => $return_path]);
+               }
 
-               $return_path = $this->session->get('return_path', '');
-               $this->session->remove('return_path');
+               $this->setForUser($a, $record, true, true);
 
                $this->baseUrl->redirect($return_path);
        }
@@ -284,67 +313,57 @@ class Authentication
         * @param bool  $interactive
         * @param bool  $login_refresh
         *
+        * @throws HTTPException\FoundException
+        * @throws HTTPException\MovedPermanentlyException
+        * @throws HTTPException\TemporaryRedirectException
+        * @throws HTTPException\ForbiddenException
+
         * @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)
        {
+               $my_url = $this->baseUrl . '/profile/' . $user_record['nickname'];
+
                $this->session->setMultiple([
                        'uid'           => $user_record['uid'],
                        'theme'         => $user_record['theme'],
                        'mobile-theme'  => $this->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'
+                       'my_url'        => $my_url,
+                       'my_address'    => $user_record['nickname'] . '@' . substr($this->baseUrl, strpos($this->baseUrl, '://') + 3),
+                       'addr'          => $this->remoteAddress,
+                       'nickname'      => $user_record['nickname'],
                ]);
 
-               Session::setVisitorsContacts();
+               $this->session->setVisitorsContacts($my_url);
 
                $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'];
+                       $a->setTimeZone($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]);
+               $contact = $this->dba->selectFirst('contact', ['id'], ['uid' => $user_record['uid'], 'self' => true]);
                if ($this->dba->isResult($contact)) {
-                       $a->contact = $contact;
-                       $a->cid     = $contact['id'];
-                       $this->session->set('cid', $a->cid);
+                       $a->setContactId($contact['id']);
+                       $this->session->set('cid', $contact['id']);
                }
 
-               header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
+               $this->setXAccMgmtStatusHeader($user_record);
 
                if ($login_initial || $login_refresh) {
-                       $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
+                       $this->dba->update('user', ['last-activity' => DateTimeFormat::utcNow('Y-m-d'), 'login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
 
                        // Set the login date for all identities of the user
-                       if (!empty($masterUid)) {
-                               $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
-                                       ['parent-uid' => $masterUid, 'account_removed' => false]);
+                       $this->dba->update('user', ['last-activity' => DateTimeFormat::utcNow('Y-m-d'), 'login_date' => DateTimeFormat::utcNow()],
+                               ['parent-uid' => $user_record['uid'], 'account_removed' => false]);
+
+                       // Regularly update suggestions
+                       if (Contact\Relation::areSuggestionsOutdated($user_record['uid'])) {
+                               Worker::add(Worker::PRIORITY_MEDIUM, 'UpdateSuggestions', $user_record['uid']);
                        }
                }
 
@@ -365,24 +384,18 @@ class Authentication
                        }
                }
 
-               $this->redirectForTwoFactorAuthentication($user_record['uid'], $a);
+               $this->redirectForTwoFactorAuthentication($user_record['uid']);
 
                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.'));
+                               DI::sysmsg()->addInfo($this->l10n->t('Welcome %s', $user_record['username']));
+                               DI::sysmsg()->addInfo($this->l10n->t('Please upload a profile photo.'));
                                $this->baseUrl->redirect('settings/profile/photo/new');
                        }
                }
 
-               $a->user = $user_record;
-
                if ($login_initial) {
-                       Hook::callAll('logged_in', $a->user);
-
-                       if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
-                               $this->baseUrl->redirect($this->session->get('return_path'));
-                       }
+                       Hook::callAll('logged_in', $user_record);
                }
        }
 
@@ -391,12 +404,11 @@ class Authentication
         * All return calls in this method skip two-factor authentication
         *
         * @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)
         * @throws HTTPException\InternalServerErrorException
         */
-       private function redirectForTwoFactorAuthentication(int $uid, App $a)
+       private function redirectForTwoFactorAuthentication(int $uid)
        {
                // Check user setting, if 2FA disabled return
                if (!$this->pConfig->get($uid, '2fa', 'verified')) {
@@ -404,7 +416,7 @@ class Authentication
                }
 
                // Check current path, if public or 2fa module return
-               if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
+               if (DI::args()->getArgc() > 0 && in_array(DI::args()->getArgv()[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
                        return;
                }
 
@@ -414,11 +426,11 @@ class Authentication
                }
 
                // Case 1b: Check for trusted browser
-               if ($this->cookie->get('trusted')) {
+               if ($this->cookie->get('2fa_cookie_hash')) {
                        // Retrieve a trusted_browser model based on cookie hash
                        $trustedBrowserRepository = new TrustedBrowser($this->dba, $this->logger);
                        try {
-                               $trustedBrowser = $trustedBrowserRepository->selectOneByHash($this->cookie->get('trusted'));
+                               $trustedBrowser = $trustedBrowserRepository->selectOneByHash($this->cookie->get('2fa_cookie_hash'));
                                // Verify record ownership
                                if ($trustedBrowser->uid === $uid) {
                                        // Update last_used date
@@ -427,10 +439,13 @@ class Authentication
                                        // Save it to the database
                                        $trustedBrowserRepository->save($trustedBrowser);
 
-                                       // Set 2fa session key and return
-                                       $this->session->set('2fa', true);
+                                       // Only use this entry, if its really trusted, otherwise just update the record and proceed
+                                       if ($trustedBrowser->trusted) {
+                                               // Set 2fa session key and return
+                                               $this->session->set('2fa', true);
 
-                                       return;
+                                               return;
+                                       }
                                } else {
                                        // Invalid trusted cookie value, removing it
                                        $this->cookie->unset('trusted');