4 * @file /src/Core/Authentication.php
7 namespace Friendica\App;
11 use Friendica\Core\Config\Configuration;
12 use Friendica\Core\Hook;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\Session;
15 use Friendica\Core\System;
16 use Friendica\Database\Database;
17 use Friendica\Database\DBA;
18 use Friendica\Model\User;
19 use Friendica\Network\HTTPException;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Network;
22 use Friendica\Util\Strings;
24 use Friendica\Core\L10n\L10n;
25 use Psr\Log\LoggerInterface;
28 * Handle Authentification, Session and Cookies
32 /** @var Configuration */
36 /** @var App\BaseURL */
42 /** @var LoggerInterface */
44 /** @var User\Cookie */
46 /** @var Session\ISession */
50 * Authentication constructor.
52 * @param Configuration $config
53 * @param App\Mode $mode
54 * @param App\BaseURL $baseUrl
56 * @param Database $dba
57 * @param LoggerInterface $logger
58 * @param User\Cookie $cookie
59 * @param Session\ISession $session
61 public function __construct(Configuration $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session)
63 $this->config = $config;
65 $this->baseUrl = $baseUrl;
68 $this->logger = $logger;
69 $this->cookie = $cookie;
70 $this->session = $session;
74 * @brief Tries to auth the user from the cookie or session
76 * @param App $a The Friendica Application context
78 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
79 * @throws Exception In case of general exceptions (like SQL Grammar)
81 public function withSession(App $a)
83 $data = $this->cookie->getData();
85 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
86 if (isset($data->uid)) {
88 $user = $this->dba->selectFirst(
94 'account_expired' => false,
95 'account_removed' => false,
99 if ($this->dba->isResult($user)) {
100 if (!$this->cookie->check($data->hash,
101 $user['password'] ?? '',
102 $user['prvkey'] ?? '')) {
103 $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
104 $this->session->delete();
105 $this->baseUrl->redirect();
109 $this->cookie->set($user['uid'], $user['password'], $user['prvkey']);
111 // Do the authentification if not done by now
112 if (!$this->session->get('authenticated')) {
113 $this->setForUser($a, $user);
115 if ($this->config->get('system', 'paranoia')) {
116 $this->session->set('addr', $data->ip);
122 if ($this->session->get('authenticated')) {
123 if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
124 $contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
125 if ($this->dba->isResult($contact)) {
126 $a->contact = $contact;
130 if ($this->session->get('uid')) {
131 // already logged in user returning
132 $check = $this->config->get('system', 'paranoia');
133 // extra paranoia - if the IP changed, log them out
134 if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
135 $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
136 'addr' => $this->session->get('addr'),
137 'remote_addr' => $_SERVER['REMOTE_ADDR']]
139 $this->session->delete();
140 $this->baseUrl->redirect();
143 $user = $this->dba->selectFirst(
147 'uid' => $this->session->get('uid'),
149 'account_expired' => false,
150 'account_removed' => false,
154 if (!$this->dba->isResult($user)) {
155 $this->session->delete();
156 $this->baseUrl->redirect();
159 // Make sure to refresh the last login time for the user if the user
160 // stays logged in for a long time, e.g. with "Remember Me"
161 $login_refresh = false;
162 if (!$this->session->get('last_login_date')) {
163 $this->session->set('last_login_date', DateTimeFormat::utcNow());
165 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
166 $this->session->set('last_login_date', DateTimeFormat::utcNow());
167 $login_refresh = true;
170 $this->setForUser($a, $user, false, false, $login_refresh);
176 * Attempts to authenticate using OpenId
178 * @param string $openid_url OpenID URL string
179 * @param bool $remember Whether to set the session remember flag
181 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
183 public function withOpenId(string $openid_url, bool $remember)
185 $noid = $this->config->get('system', 'no_openid');
187 // if it's an email address or doesn't resolve to a URL, fail.
188 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
189 notice($this->l10n->t('Login failed.') . EOL);
190 $this->baseUrl->redirect();
193 // Otherwise it's probably an openid.
195 $openid = new LightOpenID($this->baseUrl->getHostname());
196 $openid->identity = $openid_url;
197 $this->session->set('openid', $openid_url);
198 $this->session->set('remember', $remember);
199 $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
200 $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
201 System::externalRedirect($openid->authUrl());
202 } catch (Exception $e) {
203 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());
208 * Attempts to authenticate using login/password
210 * @param App $a The Friendica Application context
211 * @param string $username User name
212 * @param string $password Clear password
213 * @param bool $remember Whether to set the session remember flag
215 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
216 * @throws Exception A general Exception (like SQL Grammar exceptions)
218 public function withPassword(App $a, string $username, string $password, bool $remember)
223 'username' => $username,
224 'password' => $password,
225 'authenticated' => 0,
226 'user_record' => null
230 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
231 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
232 * and later addons should not interfere with an earlier one that succeeded.
234 Hook::callAll('authenticate', $addon_auth);
237 if ($addon_auth['authenticated']) {
238 $record = $addon_auth['user_record'];
240 if (empty($record)) {
241 throw new Exception($this->l10n->t('Login failed.'));
244 $record = $this->dba->selectFirst(
247 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
250 } catch (Exception $e) {
251 $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
252 info($this->l10n->t('Login failed. Please check your credentials.' . EOL));
253 $this->baseUrl->redirect();
257 $this->cookie->clear();
260 // if we haven't failed up this point, log them in.
261 $this->session->set('remember', $remember);
262 $this->session->set('last_login_date', DateTimeFormat::utcNow());
264 $openid_identity = $this->session->get('openid_identity');
265 $openid_server = $this->session->get('openid_server');
267 if (!empty($openid_identity) || !empty($openid_server)) {
268 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
271 $this->setForUser($a, $record, true, true);
273 $return_path = $this->session->get('return_path', '');
274 $this->session->remove('return_path');
276 $this->baseUrl->redirect($return_path);
280 * @brief Sets the provided user's authenticated session
282 * @param App $a The Friendica application context
283 * @param array $user_record The current "user" record
284 * @param bool $login_initial
285 * @param bool $interactive
286 * @param bool $login_refresh
288 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
289 * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
291 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
293 $this->session->setMultiple([
294 'uid' => $user_record['uid'],
295 'theme' => $user_record['theme'],
296 'mobile-theme' => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
297 'authenticated' => 1,
298 'page_flags' => $user_record['page-flags'],
299 'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
300 'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
301 'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
304 Session::setVisitorsContacts();
306 $member_since = strtotime($user_record['register_date']);
307 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
309 if (strlen($user_record['timezone'])) {
310 date_default_timezone_set($user_record['timezone']);
311 $a->timezone = $user_record['timezone'];
314 $masterUid = $user_record['uid'];
316 if ($this->session->get('submanage')) {
317 $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
318 if ($this->dba->isResult($user)) {
319 $masterUid = $user['uid'];
323 $a->identities = User::identities($masterUid);
325 if ($login_initial) {
326 $this->logger->info('auth_identities: ' . print_r($a->identities, true));
329 if ($login_refresh) {
330 $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
333 $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
334 if ($this->dba->isResult($contact)) {
335 $a->contact = $contact;
336 $a->cid = $contact['id'];
337 $this->session->set('cid', $a->cid);
340 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
342 if ($login_initial || $login_refresh) {
343 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
345 // Set the login date for all identities of the user
346 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
347 ['parent-uid' => $masterUid, 'account_removed' => false]);
350 if ($login_initial) {
352 * If the user specified to remember the authentication, then set a cookie
353 * that expires after one week (the default is when the browser is closed).
354 * The cookie will be renewed automatically.
355 * The week ensures that sessions will expire after some inactivity.
357 if ($this->session->get('remember')) {
358 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
359 $this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvkey']);
360 $this->session->remove('remember');
364 $this->twoFactorCheck($user_record['uid'], $a);
367 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
368 info($this->l10n->t('Welcome %s', $user_record['username']));
369 info($this->l10n->t('Please upload a profile photo.'));
370 $this->baseUrl->redirect('profile_photo/new');
372 info($this->l10n->t("Welcome back %s", $user_record['username']));
376 $a->user = $user_record;
378 if ($login_initial) {
379 Hook::callAll('logged_in', $a->user);
381 if ($a->module !== 'home' && $this->session->exists('return_path')) {
382 $this->baseUrl->redirect($this->session->get('return_path'));
388 * @param int $uid The User Identified
389 * @param App $a The Friendica Application context
391 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
393 private function twoFactorCheck(int $uid, App $a)
395 // Check user setting, if 2FA disabled return
396 if (!PConfig::get($uid, '2fa', 'verified')) {
400 // Check current path, if 2fa authentication module return
401 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
405 // Case 1: 2FA session present and valid: return
406 if ($this->session->get('2fa')) {
410 // Case 2: No valid 2FA session: redirect to code verification page
411 if ($this->mode->isAjax()) {
412 throw new HTTPException\ForbiddenException();
414 $this->baseUrl->redirect('2fa');