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