]> git.mxchange.org Git - friendica.git/blob - src/App/Authentication.php
Refactor deprecated App::isAjax() to DI::mode()->isAjax()
[friendica.git] / src / App / Authentication.php
1 <?php
2
3 /**
4  * @file /src/Core/Authentication.php
5  */
6
7 namespace Friendica\App;
8
9 use Exception;
10 use 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;
23 use LightOpenID;
24 use Friendica\Core\L10n\L10n;
25 use Psr\Log\LoggerInterface;
26
27 /**
28  * Handle Authentification, Session and Cookies
29  */
30 class Authentication
31 {
32         /** @var Configuration */
33         private $config;
34         /** @var App\Mode */
35         private $mode;
36         /** @var App\BaseURL */
37         private $baseUrl;
38         /** @var L10n */
39         private $l10n;
40         /** @var Database */
41         private $dba;
42         /** @var LoggerInterface */
43         private $logger;
44         /** @var User\Cookie */
45         private $cookie;
46         /** @var Session\ISession */
47         private $session;
48
49         /**
50          * Authentication constructor.
51          *
52          * @param Configuration   $config
53          * @param App\Mode        $mode
54          * @param App\BaseURL     $baseUrl
55          * @param L10n            $l10n
56          * @param Database        $dba
57          * @param LoggerInterface $logger
58          * @param User\Cookie     $cookie
59          * @param Session\ISession $session
60          */
61         public function __construct(Configuration $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session)
62         {
63                 $this->config  = $config;
64                 $this->mode = $mode;
65                 $this->baseUrl = $baseUrl;
66                 $this->l10n    = $l10n;
67                 $this->dba     = $dba;
68                 $this->logger  = $logger;
69                 $this->cookie = $cookie;
70                 $this->session = $session;
71         }
72
73         /**
74          * @brief Tries to auth the user from the cookie or session
75          *
76          * @param App   $a      The Friendica Application context
77          *
78          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
79          * @throws Exception In case of general exceptions (like SQL Grammar)
80          */
81         public function withSession(App $a)
82         {
83                 $data = $this->cookie->getData();
84
85                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
86                 if (isset($data->uid)) {
87
88                         $user = $this->dba->selectFirst(
89                                 'user',
90                                 [],
91                                 [
92                                         'uid'             => $data->uid,
93                                         'blocked'         => false,
94                                         'account_expired' => false,
95                                         'account_removed' => false,
96                                         'verified'        => true,
97                                 ]
98                         );
99                         if ($this->dba->isResult($user)) {
100                                 if (!$this->cookie->check($data->hash,
101                                         $user['password'] ?? '',
102                                         $user['prvkey'] ?? '')) {
103                                         $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
104                                         $this->session->delete();
105                                         $this->baseUrl->redirect();
106                                 }
107
108                                 // Renew the cookie
109                                 $this->cookie->set($user['uid'], $user['password'], $user['prvkey']);
110
111                                 // Do the authentification if not done by now
112                                 if (!$this->session->get('authenticated')) {
113                                         $this->setForUser($a, $user);
114
115                                         if ($this->config->get('system', 'paranoia')) {
116                                                 $this->session->set('addr', $data->ip);
117                                         }
118                                 }
119                         }
120                 }
121
122                 if ($this->session->get('authenticated')) {
123                         if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
124                                 $contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
125                                 if ($this->dba->isResult($contact)) {
126                                         $a->contact = $contact;
127                                 }
128                         }
129
130                         if ($this->session->get('uid')) {
131                                 // already logged in user returning
132                                 $check = $this->config->get('system', 'paranoia');
133                                 // extra paranoia - if the IP changed, log them out
134                                 if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
135                                         $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
136                                                         'addr'        => $this->session->get('addr'),
137                                                         'remote_addr' => $_SERVER['REMOTE_ADDR']]
138                                         );
139                                         $this->session->delete();
140                                         $this->baseUrl->redirect();
141                                 }
142
143                                 $user = $this->dba->selectFirst(
144                                         'user',
145                                         [],
146                                         [
147                                                 'uid'             => $this->session->get('uid'),
148                                                 'blocked'         => false,
149                                                 'account_expired' => false,
150                                                 'account_removed' => false,
151                                                 'verified'        => true,
152                                         ]
153                                 );
154                                 if (!$this->dba->isResult($user)) {
155                                         $this->session->delete();
156                                         $this->baseUrl->redirect();
157                                 }
158
159                                 // Make sure to refresh the last login time for the user if the user
160                                 // stays logged in for a long time, e.g. with "Remember Me"
161                                 $login_refresh = false;
162                                 if (!$this->session->get('last_login_date')) {
163                                         $this->session->set('last_login_date', DateTimeFormat::utcNow());
164                                 }
165                                 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
166                                         $this->session->set('last_login_date', DateTimeFormat::utcNow());
167                                         $login_refresh = true;
168                                 }
169
170                                 $this->setForUser($a, $user, false, false, $login_refresh);
171                         }
172                 }
173         }
174
175         /**
176          * Attempts to authenticate using OpenId
177          *
178          * @param string $openid_url OpenID URL string
179          * @param bool   $remember   Whether to set the session remember flag
180          *
181          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
182          */
183         public function withOpenId(string $openid_url, bool $remember)
184         {
185                 $noid = $this->config->get('system', 'no_openid');
186
187                 // if it's an email address or doesn't resolve to a URL, fail.
188                 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
189                         notice($this->l10n->t('Login failed.') . EOL);
190                         $this->baseUrl->redirect();
191                 }
192
193                 // Otherwise it's probably an openid.
194                 try {
195                         $openid           = new LightOpenID($this->baseUrl->getHostname());
196                         $openid->identity = $openid_url;
197                         $this->session->set('openid', $openid_url);
198                         $this->session->set('remember', $remember);
199                         $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
200                         $openid->optional  = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
201                         System::externalRedirect($openid->authUrl());
202                 } catch (Exception $e) {
203                         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                 }
205         }
206
207         /**
208          * Attempts to authenticate using login/password
209          *
210          * @param App    $a        The Friendica Application context
211          * @param string $username User name
212          * @param string $password Clear password
213          * @param bool   $remember Whether to set the session remember flag
214          *
215          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
216          * @throws Exception A general Exception (like SQL Grammar exceptions)
217          */
218         public function withPassword(App $a, string $username, string $password, bool $remember)
219         {
220                 $record = null;
221
222                 $addon_auth = [
223                         'username'      => $username,
224                         'password'      => $password,
225                         'authenticated' => 0,
226                         'user_record'   => null
227                 ];
228
229                 /*
230                  * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
231                  * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
232                  * and later addons should not interfere with an earlier one that succeeded.
233                  */
234                 Hook::callAll('authenticate', $addon_auth);
235
236                 try {
237                         if ($addon_auth['authenticated']) {
238                                 $record = $addon_auth['user_record'];
239
240                                 if (empty($record)) {
241                                         throw new Exception($this->l10n->t('Login failed.'));
242                                 }
243                         } else {
244                                 $record = $this->dba->selectFirst(
245                                         'user',
246                                         [],
247                                         ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
248                                 );
249                         }
250                 } catch (Exception $e) {
251                         $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
252                         info($this->l10n->t('Login failed. Please check your credentials.' . EOL));
253                         $this->baseUrl->redirect();
254                 }
255
256                 if (!$remember) {
257                         $this->cookie->clear();
258                 }
259
260                 // if we haven't failed up this point, log them in.
261                 $this->session->set('remember', $remember);
262                 $this->session->set('last_login_date', DateTimeFormat::utcNow());
263
264                 $openid_identity = $this->session->get('openid_identity');
265                 $openid_server   = $this->session->get('openid_server');
266
267                 if (!empty($openid_identity) || !empty($openid_server)) {
268                         $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
269                 }
270
271                 $this->setForUser($a, $record, true, true);
272
273                 $return_path = $this->session->get('return_path', '');
274                 $this->session->remove('return_path');
275
276                 $this->baseUrl->redirect($return_path);
277         }
278
279         /**
280          * @brief Sets the provided user's authenticated session
281          *
282          * @param App   $a           The Friendica application context
283          * @param array $user_record The current "user" record
284          * @param bool  $login_initial
285          * @param bool  $interactive
286          * @param bool  $login_refresh
287          *
288          * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
289          * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
290          */
291         public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
292         {
293                 $this->session->setMultiple([
294                         'uid'           => $user_record['uid'],
295                         'theme'         => $user_record['theme'],
296                         'mobile-theme'  => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
297                         'authenticated' => 1,
298                         'page_flags'    => $user_record['page-flags'],
299                         'my_url'        => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
300                         'my_address'    => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
301                         'addr'          => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
302                 ]);
303
304                 Session::setVisitorsContacts();
305
306                 $member_since = strtotime($user_record['register_date']);
307                 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
308
309                 if (strlen($user_record['timezone'])) {
310                         date_default_timezone_set($user_record['timezone']);
311                         $a->timezone = $user_record['timezone'];
312                 }
313
314                 $masterUid = $user_record['uid'];
315
316                 if ($this->session->get('submanage')) {
317                         $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
318                         if ($this->dba->isResult($user)) {
319                                 $masterUid = $user['uid'];
320                         }
321                 }
322
323                 $a->identities = User::identities($masterUid);
324
325                 if ($login_initial) {
326                         $this->logger->info('auth_identities: ' . print_r($a->identities, true));
327                 }
328
329                 if ($login_refresh) {
330                         $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
331                 }
332
333                 $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
334                 if ($this->dba->isResult($contact)) {
335                         $a->contact = $contact;
336                         $a->cid     = $contact['id'];
337                         $this->session->set('cid', $a->cid);
338                 }
339
340                 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
341
342                 if ($login_initial || $login_refresh) {
343                         $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
344
345                         // Set the login date for all identities of the user
346                         $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
347                                 ['parent-uid' => $masterUid, 'account_removed' => false]);
348                 }
349
350                 if ($login_initial) {
351                         /*
352                          * If the user specified to remember the authentication, then set a cookie
353                          * that expires after one week (the default is when the browser is closed).
354                          * The cookie will be renewed automatically.
355                          * The week ensures that sessions will expire after some inactivity.
356                          */;
357                         if ($this->session->get('remember')) {
358                                 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
359                                 $this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvkey']);
360                                 $this->session->remove('remember');
361                         }
362                 }
363
364                 $this->twoFactorCheck($user_record['uid'], $a);
365
366                 if ($interactive) {
367                         if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
368                                 info($this->l10n->t('Welcome %s', $user_record['username']));
369                                 info($this->l10n->t('Please upload a profile photo.'));
370                                 $this->baseUrl->redirect('profile_photo/new');
371                         } else {
372                                 info($this->l10n->t("Welcome back %s", $user_record['username']));
373                         }
374                 }
375
376                 $a->user = $user_record;
377
378                 if ($login_initial) {
379                         Hook::callAll('logged_in', $a->user);
380
381                         if ($a->module !== 'home' && $this->session->exists('return_path')) {
382                                 $this->baseUrl->redirect($this->session->get('return_path'));
383                         }
384                 }
385         }
386
387         /**
388          * @param int $uid The User Identified
389          * @param App $a   The Friendica Application context
390          *
391          * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
392          */
393         private function twoFactorCheck(int $uid, App $a)
394         {
395                 // Check user setting, if 2FA disabled return
396                 if (!PConfig::get($uid, '2fa', 'verified')) {
397                         return;
398                 }
399
400                 // Check current path, if 2fa authentication module return
401                 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
402                         return;
403                 }
404
405                 // Case 1: 2FA session present and valid: return
406                 if ($this->session->get('2fa')) {
407                         return;
408                 }
409
410                 // Case 2: No valid 2FA session: redirect to code verification page
411                 if ($this->mode->isAjax()) {
412                         throw new HTTPException\ForbiddenException();
413                 } else {
414                         $this->baseUrl->redirect('2fa');
415                 }
416         }
417 }