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 */
46 * Authentication constructor.
48 * @param Configuration $config
49 * @param App\BaseURL $baseUrl
51 * @param Database $dba
52 * @param LoggerInterface $logger
53 * @param User\Cookie $cookie
55 public function __construct(Configuration $config, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie)
57 $this->config = $config;
58 $this->baseUrl = $baseUrl;
61 $this->logger = $logger;
62 $this->cookie = $cookie;
66 * @brief Tries to auth the user from the cookie or session
68 * @param App $a The Friendica Application context
70 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
71 * @throws Exception In case of general exceptions (like SQL Grammar)
73 public function withSession(App $a)
75 $data = $this->cookie->getData();
77 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
78 if (isset($data) && isset($data->uid)) {
80 $user = $this->dba->selectFirst(
86 'account_expired' => false,
87 'account_removed' => false,
91 if (DBA::isResult($user)) {
92 if (!$this->cookie->check($data->hash,
93 $user['password'] ?? '',
94 $user['prvKey'] ?? '')) {
95 $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
97 $this->baseUrl->redirect();
101 $this->cookie->set($user['uid'], $user['password'], $user['prvKey']);
103 // Do the authentification if not done by now
104 if (!Session::get('authenticated')) {
105 $this->setForUser($a, $user);
107 if ($this->config->get('system', 'paranoia')) {
108 Session::set('addr', $data->ip);
114 if (Session::get('authenticated')) {
115 if (Session::get('visitor_id') && !Session::get('uid')) {
116 $contact = $this->dba->selectFirst('contact', [], ['id' => Session::get('visitor_id')]);
117 if ($this->dba->isResult($contact)) {
118 $a->contact = $contact;
122 if (Session::get('uid')) {
123 // already logged in user returning
124 $check = $this->config->get('system', 'paranoia');
125 // extra paranoia - if the IP changed, log them out
126 if ($check && (Session::get('addr') != $_SERVER['REMOTE_ADDR'])) {
127 $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
128 'addr' => Session::get('addr'),
129 'remote_addr' => $_SERVER['REMOTE_ADDR']]
132 $this->baseUrl->redirect();
135 $user = $this->dba->selectFirst(
139 'uid' => Session::get('uid'),
141 'account_expired' => false,
142 'account_removed' => false,
146 if (!$this->dba->isResult($user)) {
148 $this->baseUrl->redirect();
151 // Make sure to refresh the last login time for the user if the user
152 // stays logged in for a long time, e.g. with "Remember Me"
153 $login_refresh = false;
154 if (!Session::get('last_login_date')) {
155 Session::set('last_login_date', DateTimeFormat::utcNow());
157 if (strcmp(DateTimeFormat::utc('now - 12 hours'), Session::get('last_login_date')) > 0) {
158 Session::set('last_login_date', DateTimeFormat::utcNow());
159 $login_refresh = true;
162 $this->setForUser($a, $user, false, false, $login_refresh);
168 * Attempts to authenticate using OpenId
170 * @param string $openid_url OpenID URL string
171 * @param bool $remember Whether to set the session remember flag
173 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
175 public function withOpenId(string $openid_url, bool $remember)
177 $noid = $this->config->get('system', 'no_openid');
179 // if it's an email address or doesn't resolve to a URL, fail.
180 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
181 notice($this->l10n->t('Login failed.') . EOL);
182 $this->baseUrl->redirect();
185 // Otherwise it's probably an openid.
187 $openid = new LightOpenID($this->baseUrl->getHostname());
188 $openid->identity = $openid_url;
189 Session::set('openid', $openid_url);
190 Session::set('remember', $remember);
191 $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
192 $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
193 System::externalRedirect($openid->authUrl());
194 } catch (Exception $e) {
195 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());
200 * Attempts to authenticate using login/password
202 * @param App $a The Friendica Application context
203 * @param string $username User name
204 * @param string $password Clear password
205 * @param bool $remember Whether to set the session remember flag
207 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
208 * @throws Exception A general Exception (like SQL Grammar exceptions)
210 public function withPassword(App $a, string $username, string $password, bool $remember)
215 'username' => $username,
216 'password' => $password,
217 'authenticated' => 0,
218 'user_record' => null
222 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
223 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
224 * and later addons should not interfere with an earlier one that succeeded.
226 Hook::callAll('authenticate', $addon_auth);
229 if ($addon_auth['authenticated']) {
230 $record = $addon_auth['user_record'];
232 if (empty($record)) {
233 throw new Exception($this->l10n->t('Login failed.'));
236 $record = $this->dba->selectFirst(
239 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
242 } catch (Exception $e) {
243 $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
244 info($this->l10n->t('Login failed. Please check your credentials.' . EOL));
245 $this->baseUrl->redirect();
249 $this->cookie->clear();
252 // if we haven't failed up this point, log them in.
253 Session::set('remember', $remember);
254 Session::set('last_login_date', DateTimeFormat::utcNow());
256 $openid_identity = Session::get('openid_identity');
257 $openid_server = Session::get('openid_server');
259 if (!empty($openid_identity) || !empty($openid_server)) {
260 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
263 $this->setForUser($a, $record, true, true);
265 $return_path = Session::get('return_path', '');
266 Session::remove('return_path');
268 $this->baseUrl->redirect($return_path);
272 * @brief Sets the provided user's authenticated session
274 * @param App $a The Friendica application context
275 * @param array $user_record The current "user" record
276 * @param bool $login_initial
277 * @param bool $interactive
278 * @param bool $login_refresh
280 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
281 * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
283 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
285 Session::setMultiple([
286 'uid' => $user_record['uid'],
287 'theme' => $user_record['theme'],
288 'mobile-theme' => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
289 'authenticated' => 1,
290 'page_flags' => $user_record['page-flags'],
291 'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
292 'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
293 'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
296 Session::setVisitorsContacts();
298 $member_since = strtotime($user_record['register_date']);
299 Session::set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
301 if (strlen($user_record['timezone'])) {
302 date_default_timezone_set($user_record['timezone']);
303 $a->timezone = $user_record['timezone'];
306 $masterUid = $user_record['uid'];
308 if (Session::get('submanage')) {
309 $user = $this->dba->selectFirst('user', ['uid'], ['uid' => Session::get('submanage')]);
310 if ($this->dba->isResult($user)) {
311 $masterUid = $user['uid'];
315 $a->identities = User::identities($masterUid);
317 if ($login_initial) {
318 $this->logger->info('auth_identities: ' . print_r($a->identities, true));
321 if ($login_refresh) {
322 $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
325 $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
326 if ($this->dba->isResult($contact)) {
327 $a->contact = $contact;
328 $a->cid = $contact['id'];
329 Session::set('cid', $a->cid);
332 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
334 if ($login_initial || $login_refresh) {
335 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
337 // Set the login date for all identities of the user
338 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
339 ['parent-uid' => $masterUid, 'account_removed' => false]);
342 if ($login_initial) {
344 * If the user specified to remember the authentication, then set a cookie
345 * that expires after one week (the default is when the browser is closed).
346 * The cookie will be renewed automatically.
347 * The week ensures that sessions will expire after some inactivity.
349 if (Session::get('remember')) {
350 $a->getLogger()->info('Injecting cookie for remembered user ' . $user_record['nickname']);
351 $this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvKey']);
352 Session::remove('remember');
356 $this->twoFactorCheck($user_record['uid'], $a);
359 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
360 info($this->l10n->t('Welcome %s', $user_record['username']));
361 info($this->l10n->t('Please upload a profile photo.'));
362 $this->baseUrl->redirect('profile_photo/new');
364 info($this->l10n->t("Welcome back %s", $user_record['username']));
368 $a->user = $user_record;
370 if ($login_initial) {
371 Hook::callAll('logged_in', $a->user);
373 if ($a->module !== 'home' && Session::exists('return_path')) {
374 $this->baseUrl->redirect(Session::get('return_path'));
380 * @param int $uid The User Identified
381 * @param App $a The Friendica Application context
383 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
385 private function twoFactorCheck(int $uid, App $a)
387 // Check user setting, if 2FA disabled return
388 if (!PConfig::get($uid, '2fa', 'verified')) {
392 // Check current path, if 2fa authentication module return
393 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
397 // Case 1: 2FA session present and valid: return
398 if (Session::get('2fa')) {
402 // Case 2: No valid 2FA session: redirect to code verification page
404 throw new HTTPException\ForbiddenException();
406 $a->internalRedirect('2fa');