4 * @file /src/Core/Authentication.php
7 namespace Friendica\App;
11 use Friendica\Core\Config\IConfiguration;
12 use Friendica\Core\Config\IPConfiguration;
13 use Friendica\Core\Hook;
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 */
49 /** @var IPConfiguration */
53 * Authentication constructor.
55 * @param IConfiguration $config
56 * @param App\Mode $mode
57 * @param App\BaseURL $baseUrl
59 * @param Database $dba
60 * @param LoggerInterface $logger
61 * @param User\Cookie $cookie
62 * @param Session\ISession $session
63 * @param IPConfiguration $pConfig
65 public function __construct(IConfiguration $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session, IPConfiguration $pConfig)
67 $this->config = $config;
69 $this->baseUrl = $baseUrl;
72 $this->logger = $logger;
73 $this->cookie = $cookie;
74 $this->session = $session;
75 $this->pConfig = $pConfig;
79 * @brief Tries to auth the user from the cookie or session
81 * @param App $a The Friendica Application context
83 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
84 * @throws Exception In case of general exceptions (like SQL Grammar)
86 public function withSession(App $a)
88 $data = $this->cookie->getData();
90 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
91 if (isset($data->uid)) {
93 $user = $this->dba->selectFirst(
99 'account_expired' => false,
100 'account_removed' => false,
104 if ($this->dba->isResult($user)) {
105 if (!$this->cookie->check($data->hash,
106 $user['password'] ?? '',
107 $user['prvkey'] ?? '')) {
108 $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
109 $this->session->clear();
110 $this->cookie->clear();
111 $this->baseUrl->redirect();
115 $this->cookie->set($user['uid'], $user['password'], $user['prvkey']);
117 // Do the authentification if not done by now
118 if (!$this->session->get('authenticated')) {
119 $this->setForUser($a, $user);
121 if ($this->config->get('system', 'paranoia')) {
122 $this->session->set('addr', $data->ip);
128 if ($this->session->get('authenticated')) {
129 if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
130 $contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
131 if ($this->dba->isResult($contact)) {
132 $a->contact = $contact;
136 if ($this->session->get('uid')) {
137 // already logged in user returning
138 $check = $this->config->get('system', 'paranoia');
139 // extra paranoia - if the IP changed, log them out
140 if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
141 $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
142 'addr' => $this->session->get('addr'),
143 'remote_addr' => $_SERVER['REMOTE_ADDR']]
145 $this->session->clear();
146 $this->baseUrl->redirect();
149 $user = $this->dba->selectFirst(
153 'uid' => $this->session->get('uid'),
155 'account_expired' => false,
156 'account_removed' => false,
160 if (!$this->dba->isResult($user)) {
161 $this->session->clear();
162 $this->baseUrl->redirect();
165 // Make sure to refresh the last login time for the user if the user
166 // stays logged in for a long time, e.g. with "Remember Me"
167 $login_refresh = false;
168 if (!$this->session->get('last_login_date')) {
169 $this->session->set('last_login_date', DateTimeFormat::utcNow());
171 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
172 $this->session->set('last_login_date', DateTimeFormat::utcNow());
173 $login_refresh = true;
176 $this->setForUser($a, $user, false, false, $login_refresh);
182 * Attempts to authenticate using OpenId
184 * @param string $openid_url OpenID URL string
185 * @param bool $remember Whether to set the session remember flag
187 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
189 public function withOpenId(string $openid_url, bool $remember)
191 $noid = $this->config->get('system', 'no_openid');
193 // if it's an email address or doesn't resolve to a URL, fail.
194 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
195 notice($this->l10n->t('Login failed.') . EOL);
196 $this->baseUrl->redirect();
199 // Otherwise it's probably an openid.
201 $openid = new LightOpenID($this->baseUrl->getHostname());
202 $openid->identity = $openid_url;
203 $this->session->set('openid', $openid_url);
204 $this->session->set('remember', $remember);
205 $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
206 $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
207 System::externalRedirect($openid->authUrl());
208 } catch (Exception $e) {
209 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());
214 * Attempts to authenticate using login/password
216 * @param App $a The Friendica Application context
217 * @param string $username User name
218 * @param string $password Clear password
219 * @param bool $remember Whether to set the session remember flag
221 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
222 * @throws Exception A general Exception (like SQL Grammar exceptions)
224 public function withPassword(App $a, string $username, string $password, bool $remember)
229 'username' => $username,
230 'password' => $password,
231 'authenticated' => 0,
232 'user_record' => null
236 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
237 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
238 * and later addons should not interfere with an earlier one that succeeded.
240 Hook::callAll('authenticate', $addon_auth);
243 if ($addon_auth['authenticated']) {
244 $record = $addon_auth['user_record'];
246 if (empty($record)) {
247 throw new Exception($this->l10n->t('Login failed.'));
250 $record = $this->dba->selectFirst(
253 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
256 } catch (Exception $e) {
257 $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
258 info($this->l10n->t('Login failed. Please check your credentials.' . EOL));
259 $this->baseUrl->redirect();
263 $this->cookie->clear();
266 // if we haven't failed up this point, log them in.
267 $this->session->set('remember', $remember);
268 $this->session->set('last_login_date', DateTimeFormat::utcNow());
270 $openid_identity = $this->session->get('openid_identity');
271 $openid_server = $this->session->get('openid_server');
273 if (!empty($openid_identity) || !empty($openid_server)) {
274 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
277 $this->setForUser($a, $record, true, true);
279 $return_path = $this->session->get('return_path', '');
280 $this->session->remove('return_path');
282 $this->baseUrl->redirect($return_path);
286 * @brief Sets the provided user's authenticated session
288 * @param App $a The Friendica application context
289 * @param array $user_record The current "user" record
290 * @param bool $login_initial
291 * @param bool $interactive
292 * @param bool $login_refresh
294 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
295 * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
297 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
299 $this->session->setMultiple([
300 'uid' => $user_record['uid'],
301 'theme' => $user_record['theme'],
302 'mobile-theme' => $this->pConfig->get($user_record['uid'], 'system', 'mobile_theme'),
303 'authenticated' => 1,
304 'page_flags' => $user_record['page-flags'],
305 'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
306 'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
307 'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
310 Session::setVisitorsContacts();
312 $member_since = strtotime($user_record['register_date']);
313 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
315 if (strlen($user_record['timezone'])) {
316 date_default_timezone_set($user_record['timezone']);
317 $a->timezone = $user_record['timezone'];
320 $masterUid = $user_record['uid'];
322 if ($this->session->get('submanage')) {
323 $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
324 if ($this->dba->isResult($user)) {
325 $masterUid = $user['uid'];
329 $a->identities = User::identities($masterUid);
331 if ($login_initial) {
332 $this->logger->info('auth_identities: ' . print_r($a->identities, true));
335 if ($login_refresh) {
336 $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
339 $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
340 if ($this->dba->isResult($contact)) {
341 $a->contact = $contact;
342 $a->cid = $contact['id'];
343 $this->session->set('cid', $a->cid);
346 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
348 if ($login_initial || $login_refresh) {
349 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
351 // Set the login date for all identities of the user
352 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
353 ['parent-uid' => $masterUid, 'account_removed' => false]);
356 if ($login_initial) {
358 * If the user specified to remember the authentication, then set a cookie
359 * that expires after one week (the default is when the browser is closed).
360 * The cookie will be renewed automatically.
361 * The week ensures that sessions will expire after some inactivity.
363 if ($this->session->get('remember')) {
364 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
365 $this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvkey']);
366 $this->session->remove('remember');
370 $this->twoFactorCheck($user_record['uid'], $a);
373 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
374 info($this->l10n->t('Welcome %s', $user_record['username']));
375 info($this->l10n->t('Please upload a profile photo.'));
376 $this->baseUrl->redirect('profile_photo/new');
378 info($this->l10n->t("Welcome back %s", $user_record['username']));
382 $a->user = $user_record;
384 if ($login_initial) {
385 Hook::callAll('logged_in', $a->user);
387 if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
388 $this->baseUrl->redirect($this->session->get('return_path'));
394 * @param int $uid The User Identified
395 * @param App $a The Friendica Application context
397 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
399 private function twoFactorCheck(int $uid, App $a)
401 // Check user setting, if 2FA disabled return
402 if (!$this->pConfig->get($uid, '2fa', 'verified')) {
406 // Check current path, if 2fa authentication module return
407 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
411 // Case 1: 2FA session present and valid: return
412 if ($this->session->get('2fa')) {
416 // Case 2: No valid 2FA session: redirect to code verification page
417 if ($this->mode->isAjax()) {
418 throw new HTTPException\ForbiddenException();
420 $this->baseUrl->redirect('2fa');