]> git.mxchange.org Git - friendica.git/blob - src/App/Authentication.php
Merge pull request #8148 from annando/remote-comment
[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\IConfig;
12 use Friendica\Core\PConfig\IPConfig;
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;
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;
26 use Psr\Log\LoggerInterface;
27
28 /**
29  * Handle Authentification, Session and Cookies
30  */
31 class Authentication
32 {
33         /** @var IConfig */
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         /** @var IPConfig */
50         private $pConfig;
51
52         /**
53          * Authentication constructor.
54          *
55          * @param IConfig          $config
56          * @param App\Mode         $mode
57          * @param App\BaseURL      $baseUrl
58          * @param L10n             $l10n
59          * @param Database         $dba
60          * @param LoggerInterface  $logger
61          * @param User\Cookie      $cookie
62          * @param Session\ISession $session
63          * @param IPConfig         $pConfig
64          */
65         public function __construct(IConfig $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session, IPConfig $pConfig)
66         {
67                 $this->config  = $config;
68                 $this->mode    = $mode;
69                 $this->baseUrl = $baseUrl;
70                 $this->l10n    = $l10n;
71                 $this->dba     = $dba;
72                 $this->logger  = $logger;
73                 $this->cookie  = $cookie;
74                 $this->session = $session;
75                 $this->pConfig = $pConfig;
76         }
77
78         /**
79          * Tries to auth the user from the cookie or session
80          *
81          * @param App   $a      The Friendica Application context
82          *
83          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
84          * @throws Exception In case of general exceptions (like SQL Grammar)
85          */
86         public function withSession(App $a)
87         {
88                 $data = $this->cookie->getData();
89
90                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
91                 if (isset($data->uid)) {
92
93                         $user = $this->dba->selectFirst(
94                                 'user',
95                                 [],
96                                 [
97                                         'uid'             => $data->uid,
98                                         'blocked'         => false,
99                                         'account_expired' => false,
100                                         'account_removed' => false,
101                                         'verified'        => true,
102                                 ]
103                         );
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();
112                                 }
113
114                                 // Renew the cookie
115                                 $this->cookie->set($user['uid'], $user['password'], $user['prvkey']);
116
117                                 // Do the authentification if not done by now
118                                 if (!$this->session->get('authenticated')) {
119                                         $this->setForUser($a, $user);
120
121                                         if ($this->config->get('system', 'paranoia')) {
122                                                 $this->session->set('addr', $data->ip);
123                                         }
124                                 }
125                         }
126                 }
127
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;
133                                 }
134                         }
135
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']]
144                                         );
145                                         $this->session->clear();
146                                         $this->baseUrl->redirect();
147                                 }
148
149                                 $user = $this->dba->selectFirst(
150                                         'user',
151                                         [],
152                                         [
153                                                 'uid'             => $this->session->get('uid'),
154                                                 'blocked'         => false,
155                                                 'account_expired' => false,
156                                                 'account_removed' => false,
157                                                 'verified'        => true,
158                                         ]
159                                 );
160                                 if (!$this->dba->isResult($user)) {
161                                         $this->session->clear();
162                                         $this->baseUrl->redirect();
163                                 }
164
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());
170                                 }
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;
174                                 }
175
176                                 $this->setForUser($a, $user, false, false, $login_refresh);
177                         }
178                 }
179         }
180
181         /**
182          * Attempts to authenticate using OpenId
183          *
184          * @param string $openid_url OpenID URL string
185          * @param bool   $remember   Whether to set the session remember flag
186          *
187          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
188          */
189         public function withOpenId(string $openid_url, bool $remember)
190         {
191                 $noid = $this->config->get('system', 'no_openid');
192
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();
197                 }
198
199                 // Otherwise it's probably an openid.
200                 try {
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());
210                 }
211         }
212
213         /**
214          * Attempts to authenticate using login/password
215          *
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
220          *
221          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
222          * @throws Exception A general Exception (like SQL Grammar exceptions)
223          */
224         public function withPassword(App $a, string $username, string $password, bool $remember)
225         {
226                 $record = null;
227
228                 $addon_auth = [
229                         'username'      => $username,
230                         'password'      => $password,
231                         'authenticated' => 0,
232                         'user_record'   => null
233                 ];
234
235                 /*
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.
239                  */
240                 Hook::callAll('authenticate', $addon_auth);
241
242                 try {
243                         if ($addon_auth['authenticated']) {
244                                 $record = $addon_auth['user_record'];
245
246                                 if (empty($record)) {
247                                         throw new Exception($this->l10n->t('Login failed.'));
248                                 }
249                         } else {
250                                 $record = $this->dba->selectFirst(
251                                         'user',
252                                         [],
253                                         ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
254                                 );
255                         }
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();
260                 }
261
262                 if (!$remember) {
263                         $this->cookie->clear();
264                 }
265
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());
269
270                 $openid_identity = $this->session->get('openid_identity');
271                 $openid_server   = $this->session->get('openid_server');
272
273                 if (!empty($openid_identity) || !empty($openid_server)) {
274                         $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
275                 }
276
277                 $this->setForUser($a, $record, true, true);
278
279                 $return_path = $this->session->get('return_path', '');
280                 $this->session->remove('return_path');
281
282                 $this->baseUrl->redirect($return_path);
283         }
284
285         /**
286          * Sets the provided user's authenticated session
287          *
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
293          *
294          * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
295          * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
296          */
297         public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
298         {
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'
308                 ]);
309
310                 Session::setVisitorsContacts();
311
312                 $member_since = strtotime($user_record['register_date']);
313                 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
314
315                 if (strlen($user_record['timezone'])) {
316                         date_default_timezone_set($user_record['timezone']);
317                         $a->timezone = $user_record['timezone'];
318                 }
319
320                 $masterUid = $user_record['uid'];
321
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'];
326                         }
327                 }
328
329                 $a->identities = User::identities($masterUid);
330
331                 if ($login_initial) {
332                         $this->logger->info('auth_identities: ' . print_r($a->identities, true));
333                 }
334
335                 if ($login_refresh) {
336                         $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
337                 }
338
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);
344                 }
345
346                 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
347
348                 if ($login_initial || $login_refresh) {
349                         $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
350
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]);
354                 }
355
356                 if ($login_initial) {
357                         /*
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.
362                          */;
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');
367                         }
368                 }
369
370                 $this->twoFactorCheck($user_record['uid'], $a);
371
372                 if ($interactive) {
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('settings/profile/photo/new');
377                         } else {
378                                 info($this->l10n->t("Welcome back %s", $user_record['username']));
379                         }
380                 }
381
382                 $a->user = $user_record;
383
384                 if ($login_initial) {
385                         Hook::callAll('logged_in', $a->user);
386
387                         if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
388                                 $this->baseUrl->redirect($this->session->get('return_path'));
389                         }
390                 }
391         }
392
393         /**
394          * @param int $uid The User Identified
395          * @param App $a   The Friendica Application context
396          *
397          * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
398          */
399         private function twoFactorCheck(int $uid, App $a)
400         {
401                 // Check user setting, if 2FA disabled return
402                 if (!$this->pConfig->get($uid, '2fa', 'verified')) {
403                         return;
404                 }
405
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'])) {
408                         return;
409                 }
410
411                 // Case 1: 2FA session present and valid: return
412                 if ($this->session->get('2fa')) {
413                         return;
414                 }
415
416                 // Case 2: No valid 2FA session: redirect to code verification page
417                 if ($this->mode->isAjax()) {
418                         throw new HTTPException\ForbiddenException();
419                 } else {
420                         $this->baseUrl->redirect('2fa');
421                 }
422         }
423 }