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->delete();
106 $this->baseUrl->redirect();
110 $this->cookie->set($user['uid'], $user['password'], $user['prvkey']);
112 // Do the authentification if not done by now
113 if (!$this->session->get('authenticated')) {
114 $this->setForUser($a, $user);
116 if ($this->config->get('system', 'paranoia')) {
117 $this->session->set('addr', $data->ip);
123 if ($this->session->get('authenticated')) {
124 if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
125 $contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
126 if ($this->dba->isResult($contact)) {
127 $a->contact = $contact;
131 if ($this->session->get('uid')) {
132 // already logged in user returning
133 $check = $this->config->get('system', 'paranoia');
134 // extra paranoia - if the IP changed, log them out
135 if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
136 $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
137 'addr' => $this->session->get('addr'),
138 'remote_addr' => $_SERVER['REMOTE_ADDR']]
140 $this->session->delete();
141 $this->baseUrl->redirect();
144 $user = $this->dba->selectFirst(
148 'uid' => $this->session->get('uid'),
150 'account_expired' => false,
151 'account_removed' => false,
155 if (!$this->dba->isResult($user)) {
156 $this->session->delete();
157 $this->baseUrl->redirect();
160 // Make sure to refresh the last login time for the user if the user
161 // stays logged in for a long time, e.g. with "Remember Me"
162 $login_refresh = false;
163 if (!$this->session->get('last_login_date')) {
164 $this->session->set('last_login_date', DateTimeFormat::utcNow());
166 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
167 $this->session->set('last_login_date', DateTimeFormat::utcNow());
168 $login_refresh = true;
171 $this->setForUser($a, $user, false, false, $login_refresh);
177 * Attempts to authenticate using OpenId
179 * @param string $openid_url OpenID URL string
180 * @param bool $remember Whether to set the session remember flag
182 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
184 public function withOpenId(string $openid_url, bool $remember)
186 $noid = $this->config->get('system', 'no_openid');
188 // if it's an email address or doesn't resolve to a URL, fail.
189 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
190 notice($this->l10n->t('Login failed.') . EOL);
191 $this->baseUrl->redirect();
194 // Otherwise it's probably an openid.
196 $openid = new LightOpenID($this->baseUrl->getHostname());
197 $openid->identity = $openid_url;
198 $this->session->set('openid', $openid_url);
199 $this->session->set('remember', $remember);
200 $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
201 $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
202 System::externalRedirect($openid->authUrl());
203 } catch (Exception $e) {
204 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());
209 * Attempts to authenticate using login/password
211 * @param App $a The Friendica Application context
212 * @param string $username User name
213 * @param string $password Clear password
214 * @param bool $remember Whether to set the session remember flag
216 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
217 * @throws Exception A general Exception (like SQL Grammar exceptions)
219 public function withPassword(App $a, string $username, string $password, bool $remember)
224 'username' => $username,
225 'password' => $password,
226 'authenticated' => 0,
227 'user_record' => null
231 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
232 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
233 * and later addons should not interfere with an earlier one that succeeded.
235 Hook::callAll('authenticate', $addon_auth);
238 if ($addon_auth['authenticated']) {
239 $record = $addon_auth['user_record'];
241 if (empty($record)) {
242 throw new Exception($this->l10n->t('Login failed.'));
245 $record = $this->dba->selectFirst(
248 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
251 } catch (Exception $e) {
252 $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
253 info($this->l10n->t('Login failed. Please check your credentials.' . EOL));
254 $this->baseUrl->redirect();
258 $this->cookie->clear();
261 // if we haven't failed up this point, log them in.
262 $this->session->set('remember', $remember);
263 $this->session->set('last_login_date', DateTimeFormat::utcNow());
265 $openid_identity = $this->session->get('openid_identity');
266 $openid_server = $this->session->get('openid_server');
268 if (!empty($openid_identity) || !empty($openid_server)) {
269 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
272 $this->setForUser($a, $record, true, true);
274 $return_path = $this->session->get('return_path', '');
275 $this->session->remove('return_path');
277 $this->baseUrl->redirect($return_path);
281 * @brief Sets the provided user's authenticated session
283 * @param App $a The Friendica application context
284 * @param array $user_record The current "user" record
285 * @param bool $login_initial
286 * @param bool $interactive
287 * @param bool $login_refresh
289 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
290 * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
292 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
294 $this->session->setMultiple([
295 'uid' => $user_record['uid'],
296 'theme' => $user_record['theme'],
297 'mobile-theme' => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
298 'authenticated' => 1,
299 'page_flags' => $user_record['page-flags'],
300 'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
301 'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
302 'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
305 Session::setVisitorsContacts();
307 $member_since = strtotime($user_record['register_date']);
308 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
310 if (strlen($user_record['timezone'])) {
311 date_default_timezone_set($user_record['timezone']);
312 $a->timezone = $user_record['timezone'];
315 $masterUid = $user_record['uid'];
317 if ($this->session->get('submanage')) {
318 $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
319 if ($this->dba->isResult($user)) {
320 $masterUid = $user['uid'];
324 $a->identities = User::identities($masterUid);
326 if ($login_initial) {
327 $this->logger->info('auth_identities: ' . print_r($a->identities, true));
330 if ($login_refresh) {
331 $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
334 $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
335 if ($this->dba->isResult($contact)) {
336 $a->contact = $contact;
337 $a->cid = $contact['id'];
338 $this->session->set('cid', $a->cid);
341 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
343 if ($login_initial || $login_refresh) {
344 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
346 // Set the login date for all identities of the user
347 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
348 ['parent-uid' => $masterUid, 'account_removed' => false]);
351 if ($login_initial) {
353 * If the user specified to remember the authentication, then set a cookie
354 * that expires after one week (the default is when the browser is closed).
355 * The cookie will be renewed automatically.
356 * The week ensures that sessions will expire after some inactivity.
358 if ($this->session->get('remember')) {
359 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
360 $this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvkey']);
361 $this->session->remove('remember');
365 $this->twoFactorCheck($user_record['uid'], $a);
368 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
369 info($this->l10n->t('Welcome %s', $user_record['username']));
370 info($this->l10n->t('Please upload a profile photo.'));
371 $this->baseUrl->redirect('profile_photo/new');
373 info($this->l10n->t("Welcome back %s", $user_record['username']));
377 $a->user = $user_record;
379 if ($login_initial) {
380 Hook::callAll('logged_in', $a->user);
382 if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
383 $this->baseUrl->redirect($this->session->get('return_path'));
389 * @param int $uid The User Identified
390 * @param App $a The Friendica Application context
392 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
394 private function twoFactorCheck(int $uid, App $a)
396 // Check user setting, if 2FA disabled return
397 if (!PConfig::get($uid, '2fa', 'verified')) {
401 // Check current path, if 2fa authentication module return
402 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
406 // Case 1: 2FA session present and valid: return
407 if ($this->session->get('2fa')) {
411 // Case 2: No valid 2FA session: redirect to code verification page
412 if ($this->mode->isAjax()) {
413 throw new HTTPException\ForbiddenException();
415 $this->baseUrl->redirect('2fa');