4 * @file /src/Core/Authentication.php
7 namespace Friendica\App;
11 use Friendica\Core\Config\IConfiguration;
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;
19 use Friendica\Model\User;
20 use Friendica\Network\HTTPException;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Strings;
25 use Friendica\Core\L10n\L10n;
26 use Psr\Log\LoggerInterface;
29 * Handle Authentification, Session and Cookies
33 /** @var IConfiguration */
37 /** @var App\BaseURL */
43 /** @var LoggerInterface */
45 /** @var User\Cookie */
47 /** @var Session\ISession */
51 * Authentication constructor.
53 * @param IConfiguration $config
54 * @param App\Mode $mode
55 * @param App\BaseURL $baseUrl
57 * @param Database $dba
58 * @param LoggerInterface $logger
59 * @param User\Cookie $cookie
60 * @param Session\ISession $session
62 public function __construct(IConfiguration $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session)
64 $this->config = $config;
66 $this->baseUrl = $baseUrl;
69 $this->logger = $logger;
70 $this->cookie = $cookie;
71 $this->session = $session;
75 * @brief Tries to auth the user from the cookie or session
77 * @param App $a The Friendica Application context
79 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
80 * @throws Exception In case of general exceptions (like SQL Grammar)
82 public function withSession(App $a)
84 $data = $this->cookie->getData();
86 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
87 if (isset($data->uid)) {
89 $user = $this->dba->selectFirst(
95 'account_expired' => false,
96 'account_removed' => false,
100 if ($this->dba->isResult($user)) {
101 if (!$this->cookie->check($data->hash,
102 $user['password'] ?? '',
103 $user['prvkey'] ?? '')) {
104 $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
105 $this->session->clear();
106 $this->cookie->clear();
107 $this->baseUrl->redirect();
111 $this->cookie->set($user['uid'], $user['password'], $user['prvkey']);
113 // Do the authentification if not done by now
114 if (!$this->session->get('authenticated')) {
115 $this->setForUser($a, $user);
117 if ($this->config->get('system', 'paranoia')) {
118 $this->session->set('addr', $data->ip);
124 if ($this->session->get('authenticated')) {
125 if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
126 $contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
127 if ($this->dba->isResult($contact)) {
128 $a->contact = $contact;
132 if ($this->session->get('uid')) {
133 // already logged in user returning
134 $check = $this->config->get('system', 'paranoia');
135 // extra paranoia - if the IP changed, log them out
136 if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
137 $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
138 'addr' => $this->session->get('addr'),
139 'remote_addr' => $_SERVER['REMOTE_ADDR']]
141 $this->session->clear();
142 $this->baseUrl->redirect();
145 $user = $this->dba->selectFirst(
149 'uid' => $this->session->get('uid'),
151 'account_expired' => false,
152 'account_removed' => false,
156 if (!$this->dba->isResult($user)) {
157 $this->session->clear();
158 $this->baseUrl->redirect();
161 // Make sure to refresh the last login time for the user if the user
162 // stays logged in for a long time, e.g. with "Remember Me"
163 $login_refresh = false;
164 if (!$this->session->get('last_login_date')) {
165 $this->session->set('last_login_date', DateTimeFormat::utcNow());
167 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
168 $this->session->set('last_login_date', DateTimeFormat::utcNow());
169 $login_refresh = true;
172 $this->setForUser($a, $user, false, false, $login_refresh);
178 * Attempts to authenticate using OpenId
180 * @param string $openid_url OpenID URL string
181 * @param bool $remember Whether to set the session remember flag
183 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
185 public function withOpenId(string $openid_url, bool $remember)
187 $noid = $this->config->get('system', 'no_openid');
189 // if it's an email address or doesn't resolve to a URL, fail.
190 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
191 notice($this->l10n->t('Login failed.') . EOL);
192 $this->baseUrl->redirect();
195 // Otherwise it's probably an openid.
197 $openid = new LightOpenID($this->baseUrl->getHostname());
198 $openid->identity = $openid_url;
199 $this->session->set('openid', $openid_url);
200 $this->session->set('remember', $remember);
201 $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
202 $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
203 System::externalRedirect($openid->authUrl());
204 } catch (Exception $e) {
205 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());
210 * Attempts to authenticate using login/password
212 * @param App $a The Friendica Application context
213 * @param string $username User name
214 * @param string $password Clear password
215 * @param bool $remember Whether to set the session remember flag
217 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
218 * @throws Exception A general Exception (like SQL Grammar exceptions)
220 public function withPassword(App $a, string $username, string $password, bool $remember)
225 'username' => $username,
226 'password' => $password,
227 'authenticated' => 0,
228 'user_record' => null
232 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
233 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
234 * and later addons should not interfere with an earlier one that succeeded.
236 Hook::callAll('authenticate', $addon_auth);
239 if ($addon_auth['authenticated']) {
240 $record = $addon_auth['user_record'];
242 if (empty($record)) {
243 throw new Exception($this->l10n->t('Login failed.'));
246 $record = $this->dba->selectFirst(
249 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
252 } catch (Exception $e) {
253 $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
254 info($this->l10n->t('Login failed. Please check your credentials.' . EOL));
255 $this->baseUrl->redirect();
259 $this->cookie->clear();
262 // if we haven't failed up this point, log them in.
263 $this->session->set('remember', $remember);
264 $this->session->set('last_login_date', DateTimeFormat::utcNow());
266 $openid_identity = $this->session->get('openid_identity');
267 $openid_server = $this->session->get('openid_server');
269 if (!empty($openid_identity) || !empty($openid_server)) {
270 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
273 $this->setForUser($a, $record, true, true);
275 $return_path = $this->session->get('return_path', '');
276 $this->session->remove('return_path');
278 $this->baseUrl->redirect($return_path);
282 * @brief Sets the provided user's authenticated session
284 * @param App $a The Friendica application context
285 * @param array $user_record The current "user" record
286 * @param bool $login_initial
287 * @param bool $interactive
288 * @param bool $login_refresh
290 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
291 * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
293 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
295 $this->session->setMultiple([
296 'uid' => $user_record['uid'],
297 'theme' => $user_record['theme'],
298 'mobile-theme' => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
299 'authenticated' => 1,
300 'page_flags' => $user_record['page-flags'],
301 'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
302 'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
303 'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
306 Session::setVisitorsContacts();
308 $member_since = strtotime($user_record['register_date']);
309 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
311 if (strlen($user_record['timezone'])) {
312 date_default_timezone_set($user_record['timezone']);
313 $a->timezone = $user_record['timezone'];
316 $masterUid = $user_record['uid'];
318 if ($this->session->get('submanage')) {
319 $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
320 if ($this->dba->isResult($user)) {
321 $masterUid = $user['uid'];
325 $a->identities = User::identities($masterUid);
327 if ($login_initial) {
328 $this->logger->info('auth_identities: ' . print_r($a->identities, true));
331 if ($login_refresh) {
332 $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
335 $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
336 if ($this->dba->isResult($contact)) {
337 $a->contact = $contact;
338 $a->cid = $contact['id'];
339 $this->session->set('cid', $a->cid);
342 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
344 if ($login_initial || $login_refresh) {
345 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
347 // Set the login date for all identities of the user
348 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
349 ['parent-uid' => $masterUid, 'account_removed' => false]);
352 if ($login_initial) {
354 * If the user specified to remember the authentication, then set a cookie
355 * that expires after one week (the default is when the browser is closed).
356 * The cookie will be renewed automatically.
357 * The week ensures that sessions will expire after some inactivity.
359 if ($this->session->get('remember')) {
360 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
361 $this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvkey']);
362 $this->session->remove('remember');
366 $this->twoFactorCheck($user_record['uid'], $a);
369 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
370 info($this->l10n->t('Welcome %s', $user_record['username']));
371 info($this->l10n->t('Please upload a profile photo.'));
372 $this->baseUrl->redirect('profile_photo/new');
374 info($this->l10n->t("Welcome back %s", $user_record['username']));
378 $a->user = $user_record;
380 if ($login_initial) {
381 Hook::callAll('logged_in', $a->user);
383 if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
384 $this->baseUrl->redirect($this->session->get('return_path'));
390 * @param int $uid The User Identified
391 * @param App $a The Friendica Application context
393 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
395 private function twoFactorCheck(int $uid, App $a)
397 // Check user setting, if 2FA disabled return
398 if (!PConfig::get($uid, '2fa', 'verified')) {
402 // Check current path, if 2fa authentication module return
403 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
407 // Case 1: 2FA session present and valid: return
408 if ($this->session->get('2fa')) {
412 // Case 2: No valid 2FA session: redirect to code verification page
413 if ($this->mode->isAjax()) {
414 throw new HTTPException\ForbiddenException();
416 $this->baseUrl->redirect('2fa');