3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\App;
26 use Friendica\Core\Config\IConfig;
27 use Friendica\Core\PConfig\IPConfig;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Session;
30 use Friendica\Core\System;
31 use Friendica\Database\Database;
32 use Friendica\Database\DBA;
34 use Friendica\Model\User;
35 use Friendica\Network\HTTPException;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
40 use Friendica\Core\L10n;
41 use Psr\Log\LoggerInterface;
44 * Handle Authentification, Session and Cookies
52 /** @var App\BaseURL */
58 /** @var LoggerInterface */
60 /** @var User\Cookie */
62 /** @var Session\ISession */
68 * Authentication constructor.
70 * @param IConfig $config
71 * @param App\Mode $mode
72 * @param App\BaseURL $baseUrl
74 * @param Database $dba
75 * @param LoggerInterface $logger
76 * @param User\Cookie $cookie
77 * @param Session\ISession $session
78 * @param IPConfig $pConfig
80 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)
82 $this->config = $config;
84 $this->baseUrl = $baseUrl;
87 $this->logger = $logger;
88 $this->cookie = $cookie;
89 $this->session = $session;
90 $this->pConfig = $pConfig;
94 * Tries to auth the user from the cookie or session
96 * @param App $a The Friendica Application context
98 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
99 * @throws Exception In case of general exceptions (like SQL Grammar)
101 public function withSession(App $a)
103 $data = $this->cookie->getData();
105 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
106 if (isset($data->uid)) {
108 $user = $this->dba->selectFirst(
114 'account_expired' => false,
115 'account_removed' => false,
119 if ($this->dba->isResult($user)) {
120 if (!$this->cookie->check($data->hash,
121 $user['password'] ?? '',
122 $user['prvkey'] ?? '')) {
123 $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
124 $this->session->clear();
125 $this->cookie->clear();
126 $this->baseUrl->redirect();
130 $this->cookie->set($user['uid'], $user['password'], $user['prvkey']);
132 // Do the authentification if not done by now
133 if (!$this->session->get('authenticated')) {
134 $this->setForUser($a, $user);
136 if ($this->config->get('system', 'paranoia')) {
137 $this->session->set('addr', $data->ip);
143 if ($this->session->get('authenticated')) {
144 if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
145 $contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
146 if ($this->dba->isResult($contact)) {
147 $a->contact = $contact;
151 if ($this->session->get('uid')) {
152 // already logged in user returning
153 $check = $this->config->get('system', 'paranoia');
154 // extra paranoia - if the IP changed, log them out
155 if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
156 $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
157 'addr' => $this->session->get('addr'),
158 'remote_addr' => $_SERVER['REMOTE_ADDR']]
160 $this->session->clear();
161 $this->baseUrl->redirect();
164 $user = $this->dba->selectFirst(
168 'uid' => $this->session->get('uid'),
170 'account_expired' => false,
171 'account_removed' => false,
175 if (!$this->dba->isResult($user)) {
176 $this->session->clear();
177 $this->baseUrl->redirect();
180 // Make sure to refresh the last login time for the user if the user
181 // stays logged in for a long time, e.g. with "Remember Me"
182 $login_refresh = false;
183 if (!$this->session->get('last_login_date')) {
184 $this->session->set('last_login_date', DateTimeFormat::utcNow());
186 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
187 $this->session->set('last_login_date', DateTimeFormat::utcNow());
188 $login_refresh = true;
191 $this->setForUser($a, $user, false, false, $login_refresh);
197 * Attempts to authenticate using OpenId
199 * @param string $openid_url OpenID URL string
200 * @param bool $remember Whether to set the session remember flag
202 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
204 public function withOpenId(string $openid_url, bool $remember)
206 $noid = $this->config->get('system', 'no_openid');
208 // if it's an email address or doesn't resolve to a URL, fail.
209 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
210 notice($this->l10n->t('Login failed.'));
211 $this->baseUrl->redirect();
214 // Otherwise it's probably an openid.
216 $openid = new LightOpenID($this->baseUrl->getHostname());
217 $openid->identity = $openid_url;
218 $this->session->set('openid', $openid_url);
219 $this->session->set('remember', $remember);
220 $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
221 $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
222 System::externalRedirect($openid->authUrl());
223 } catch (Exception $e) {
224 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());
229 * Attempts to authenticate using login/password
231 * @param App $a The Friendica Application context
232 * @param string $username User name
233 * @param string $password Clear password
234 * @param bool $remember Whether to set the session remember flag
236 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
237 * @throws Exception A general Exception (like SQL Grammar exceptions)
239 public function withPassword(App $a, string $username, string $password, bool $remember)
244 'username' => $username,
245 'password' => $password,
246 'authenticated' => 0,
247 'user_record' => null
251 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
252 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
253 * and later addons should not interfere with an earlier one that succeeded.
255 Hook::callAll('authenticate', $addon_auth);
258 if ($addon_auth['authenticated']) {
259 $record = $addon_auth['user_record'];
261 if (empty($record)) {
262 throw new Exception($this->l10n->t('Login failed.'));
265 $record = $this->dba->selectFirst(
268 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
271 } catch (Exception $e) {
272 $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
273 notice($this->l10n->t('Login failed. Please check your credentials.'));
274 $this->baseUrl->redirect();
278 $this->cookie->clear();
281 // if we haven't failed up this point, log them in.
282 $this->session->set('remember', $remember);
283 $this->session->set('last_login_date', DateTimeFormat::utcNow());
285 $openid_identity = $this->session->get('openid_identity');
286 $openid_server = $this->session->get('openid_server');
288 if (!empty($openid_identity) || !empty($openid_server)) {
289 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
292 $this->setForUser($a, $record, true, true);
294 $return_path = $this->session->get('return_path', '');
295 $this->session->remove('return_path');
297 $this->baseUrl->redirect($return_path);
301 * Sets the provided user's authenticated session
303 * @param App $a The Friendica application context
304 * @param array $user_record The current "user" record
305 * @param bool $login_initial
306 * @param bool $interactive
307 * @param bool $login_refresh
309 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
310 * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
312 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
314 $this->session->setMultiple([
315 'uid' => $user_record['uid'],
316 'theme' => $user_record['theme'],
317 'mobile-theme' => $this->pConfig->get($user_record['uid'], 'system', 'mobile_theme'),
318 'authenticated' => 1,
319 'page_flags' => $user_record['page-flags'],
320 'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
321 'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
322 'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
325 Session::setVisitorsContacts();
327 $member_since = strtotime($user_record['register_date']);
328 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
330 if (strlen($user_record['timezone'])) {
331 date_default_timezone_set($user_record['timezone']);
332 $a->timezone = $user_record['timezone'];
335 $masterUid = $user_record['uid'];
337 if ($this->session->get('submanage')) {
338 $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
339 if ($this->dba->isResult($user)) {
340 $masterUid = $user['uid'];
344 $a->identities = User::identities($masterUid);
346 if ($login_initial) {
347 $this->logger->info('auth_identities: ' . print_r($a->identities, true));
350 if ($login_refresh) {
351 $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
354 $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
355 if ($this->dba->isResult($contact)) {
356 $a->contact = $contact;
357 $a->cid = $contact['id'];
358 $this->session->set('cid', $a->cid);
361 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
363 if ($login_initial || $login_refresh) {
364 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
366 // Set the login date for all identities of the user
367 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
368 ['parent-uid' => $masterUid, 'account_removed' => false]);
371 if ($login_initial) {
373 * If the user specified to remember the authentication, then set a cookie
374 * that expires after one week (the default is when the browser is closed).
375 * The cookie will be renewed automatically.
376 * The week ensures that sessions will expire after some inactivity.
378 if ($this->session->get('remember')) {
379 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
380 $this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvkey']);
381 $this->session->remove('remember');
385 $this->twoFactorCheck($user_record['uid'], $a);
388 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
389 info($this->l10n->t('Welcome %s', $user_record['username']));
390 info($this->l10n->t('Please upload a profile photo.'));
391 $this->baseUrl->redirect('settings/profile/photo/new');
395 $a->user = $user_record;
397 if ($login_initial) {
398 Hook::callAll('logged_in', $a->user);
400 if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
401 $this->baseUrl->redirect($this->session->get('return_path'));
407 * @param int $uid The User Identified
408 * @param App $a The Friendica Application context
410 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
412 private function twoFactorCheck(int $uid, App $a)
414 // Check user setting, if 2FA disabled return
415 if (!$this->pConfig->get($uid, '2fa', 'verified')) {
419 // Check current path, if 2fa authentication module return
420 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
424 // Case 1: 2FA session present and valid: return
425 if ($this->session->get('2fa')) {
429 // Case 2: No valid 2FA session: redirect to code verification page
430 if ($this->mode->isAjax()) {
431 throw new HTTPException\ForbiddenException();
433 $this->baseUrl->redirect('2fa');