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 */
34 /** @var App\BaseURL */
40 /** @var LoggerInterface */
42 /** @var User\Cookie */
44 /** @var Session\ISession */
48 * Authentication constructor.
50 * @param Configuration $config
51 * @param App\BaseURL $baseUrl
53 * @param Database $dba
54 * @param LoggerInterface $logger
55 * @param User\Cookie $cookie
56 * @param Session\ISession $session
58 public function __construct(Configuration $config, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session)
60 $this->config = $config;
61 $this->baseUrl = $baseUrl;
64 $this->logger = $logger;
65 $this->cookie = $cookie;
66 $this->session = $session;
70 * @brief Tries to auth the user from the cookie or session
72 * @param App $a The Friendica Application context
74 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
75 * @throws Exception In case of general exceptions (like SQL Grammar)
77 public function withSession(App $a)
79 $data = $this->cookie->getData();
81 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
82 if (isset($data->uid)) {
84 $user = $this->dba->selectFirst(
90 'account_expired' => false,
91 'account_removed' => false,
95 if ($this->dba->isResult($user)) {
96 if (!$this->cookie->check($data->hash,
97 $user['password'] ?? '',
98 $user['prvkey'] ?? '')) {
99 $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
100 $this->session->delete();
101 $this->baseUrl->redirect();
105 $this->cookie->set($user['uid'], $user['password'], $user['prvkey']);
107 // Do the authentification if not done by now
108 if (!$this->session->get('authenticated')) {
109 $this->setForUser($a, $user);
111 if ($this->config->get('system', 'paranoia')) {
112 $this->session->set('addr', $data->ip);
118 if ($this->session->get('authenticated')) {
119 if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
120 $contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
121 if ($this->dba->isResult($contact)) {
122 $a->contact = $contact;
126 if ($this->session->get('uid')) {
127 // already logged in user returning
128 $check = $this->config->get('system', 'paranoia');
129 // extra paranoia - if the IP changed, log them out
130 if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
131 $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
132 'addr' => $this->session->get('addr'),
133 'remote_addr' => $_SERVER['REMOTE_ADDR']]
135 $this->session->delete();
136 $this->baseUrl->redirect();
139 $user = $this->dba->selectFirst(
143 'uid' => $this->session->get('uid'),
145 'account_expired' => false,
146 'account_removed' => false,
150 if (!$this->dba->isResult($user)) {
151 $this->session->delete();
152 $this->baseUrl->redirect();
155 // Make sure to refresh the last login time for the user if the user
156 // stays logged in for a long time, e.g. with "Remember Me"
157 $login_refresh = false;
158 if (!$this->session->get('last_login_date')) {
159 $this->session->set('last_login_date', DateTimeFormat::utcNow());
161 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
162 $this->session->set('last_login_date', DateTimeFormat::utcNow());
163 $login_refresh = true;
166 $this->setForUser($a, $user, false, false, $login_refresh);
172 * Attempts to authenticate using OpenId
174 * @param string $openid_url OpenID URL string
175 * @param bool $remember Whether to set the session remember flag
177 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
179 public function withOpenId(string $openid_url, bool $remember)
181 $noid = $this->config->get('system', 'no_openid');
183 // if it's an email address or doesn't resolve to a URL, fail.
184 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
185 notice($this->l10n->t('Login failed.') . EOL);
186 $this->baseUrl->redirect();
189 // Otherwise it's probably an openid.
191 $openid = new LightOpenID($this->baseUrl->getHostname());
192 $openid->identity = $openid_url;
193 $this->session->set('openid', $openid_url);
194 $this->session->set('remember', $remember);
195 $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
196 $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
197 System::externalRedirect($openid->authUrl());
198 } catch (Exception $e) {
199 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());
204 * Attempts to authenticate using login/password
206 * @param App $a The Friendica Application context
207 * @param string $username User name
208 * @param string $password Clear password
209 * @param bool $remember Whether to set the session remember flag
211 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
212 * @throws Exception A general Exception (like SQL Grammar exceptions)
214 public function withPassword(App $a, string $username, string $password, bool $remember)
219 'username' => $username,
220 'password' => $password,
221 'authenticated' => 0,
222 'user_record' => null
226 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
227 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
228 * and later addons should not interfere with an earlier one that succeeded.
230 Hook::callAll('authenticate', $addon_auth);
233 if ($addon_auth['authenticated']) {
234 $record = $addon_auth['user_record'];
236 if (empty($record)) {
237 throw new Exception($this->l10n->t('Login failed.'));
240 $record = $this->dba->selectFirst(
243 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
246 } catch (Exception $e) {
247 $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
248 info($this->l10n->t('Login failed. Please check your credentials.' . EOL));
249 $this->baseUrl->redirect();
253 $this->cookie->clear();
256 // if we haven't failed up this point, log them in.
257 $this->session->set('remember', $remember);
258 $this->session->set('last_login_date', DateTimeFormat::utcNow());
260 $openid_identity = $this->session->get('openid_identity');
261 $openid_server = $this->session->get('openid_server');
263 if (!empty($openid_identity) || !empty($openid_server)) {
264 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
267 $this->setForUser($a, $record, true, true);
269 $return_path = $this->session->get('return_path', '');
270 $this->session->remove('return_path');
272 $this->baseUrl->redirect($return_path);
276 * @brief Sets the provided user's authenticated session
278 * @param App $a The Friendica application context
279 * @param array $user_record The current "user" record
280 * @param bool $login_initial
281 * @param bool $interactive
282 * @param bool $login_refresh
284 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
285 * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
287 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
289 $this->session->setMultiple([
290 'uid' => $user_record['uid'],
291 'theme' => $user_record['theme'],
292 'mobile-theme' => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
293 'authenticated' => 1,
294 'page_flags' => $user_record['page-flags'],
295 'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
296 'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
297 'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
300 Session::setVisitorsContacts();
302 $member_since = strtotime($user_record['register_date']);
303 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
305 if (strlen($user_record['timezone'])) {
306 date_default_timezone_set($user_record['timezone']);
307 $a->timezone = $user_record['timezone'];
310 $masterUid = $user_record['uid'];
312 if ($this->session->get('submanage')) {
313 $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
314 if ($this->dba->isResult($user)) {
315 $masterUid = $user['uid'];
319 $a->identities = User::identities($masterUid);
321 if ($login_initial) {
322 $this->logger->info('auth_identities: ' . print_r($a->identities, true));
325 if ($login_refresh) {
326 $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
329 $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
330 if ($this->dba->isResult($contact)) {
331 $a->contact = $contact;
332 $a->cid = $contact['id'];
333 $this->session->set('cid', $a->cid);
336 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
338 if ($login_initial || $login_refresh) {
339 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
341 // Set the login date for all identities of the user
342 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
343 ['parent-uid' => $masterUid, 'account_removed' => false]);
346 if ($login_initial) {
348 * If the user specified to remember the authentication, then set a cookie
349 * that expires after one week (the default is when the browser is closed).
350 * The cookie will be renewed automatically.
351 * The week ensures that sessions will expire after some inactivity.
353 if ($this->session->get('remember')) {
354 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
355 $this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvkey']);
356 $this->session->remove('remember');
360 $this->twoFactorCheck($user_record['uid'], $a);
363 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
364 info($this->l10n->t('Welcome %s', $user_record['username']));
365 info($this->l10n->t('Please upload a profile photo.'));
366 $this->baseUrl->redirect('profile_photo/new');
368 info($this->l10n->t("Welcome back %s", $user_record['username']));
372 $a->user = $user_record;
374 if ($login_initial) {
375 Hook::callAll('logged_in', $a->user);
377 if ($a->module !== 'home' && $this->session->exists('return_path')) {
378 $this->baseUrl->redirect($this->session->get('return_path'));
384 * @param int $uid The User Identified
385 * @param App $a The Friendica Application context
387 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
389 private function twoFactorCheck(int $uid, App $a)
391 // Check user setting, if 2FA disabled return
392 if (!PConfig::get($uid, '2fa', 'verified')) {
396 // Check current path, if 2fa authentication module return
397 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
401 // Case 1: 2FA session present and valid: return
402 if ($this->session->get('2fa')) {
406 // Case 2: No valid 2FA session: redirect to code verification page
408 throw new HTTPException\ForbiddenException();
410 $a->internalRedirect('2fa');