]> git.mxchange.org Git - friendica.git/blob - src/App/Authentication.php
Update wrong references to ISession::delete
[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->baseUrl->redirect();
107                                 }
108
109                                 // Renew the cookie
110                                 $this->cookie->set($user['uid'], $user['password'], $user['prvkey']);
111
112                                 // Do the authentification if not done by now
113                                 if (!$this->session->get('authenticated')) {
114                                         $this->setForUser($a, $user);
115
116                                         if ($this->config->get('system', 'paranoia')) {
117                                                 $this->session->set('addr', $data->ip);
118                                         }
119                                 }
120                         }
121                 }
122
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;
128                                 }
129                         }
130
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']]
139                                         );
140                                         $this->session->clear();
141                                         $this->baseUrl->redirect();
142                                 }
143
144                                 $user = $this->dba->selectFirst(
145                                         'user',
146                                         [],
147                                         [
148                                                 'uid'             => $this->session->get('uid'),
149                                                 'blocked'         => false,
150                                                 'account_expired' => false,
151                                                 'account_removed' => false,
152                                                 'verified'        => true,
153                                         ]
154                                 );
155                                 if (!$this->dba->isResult($user)) {
156                                         $this->session->clear();
157                                         $this->baseUrl->redirect();
158                                 }
159
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());
165                                 }
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;
169                                 }
170
171                                 $this->setForUser($a, $user, false, false, $login_refresh);
172                         }
173                 }
174         }
175
176         /**
177          * Attempts to authenticate using OpenId
178          *
179          * @param string $openid_url OpenID URL string
180          * @param bool   $remember   Whether to set the session remember flag
181          *
182          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
183          */
184         public function withOpenId(string $openid_url, bool $remember)
185         {
186                 $noid = $this->config->get('system', 'no_openid');
187
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();
192                 }
193
194                 // Otherwise it's probably an openid.
195                 try {
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());
205                 }
206         }
207
208         /**
209          * Attempts to authenticate using login/password
210          *
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
215          *
216          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
217          * @throws Exception A general Exception (like SQL Grammar exceptions)
218          */
219         public function withPassword(App $a, string $username, string $password, bool $remember)
220         {
221                 $record = null;
222
223                 $addon_auth = [
224                         'username'      => $username,
225                         'password'      => $password,
226                         'authenticated' => 0,
227                         'user_record'   => null
228                 ];
229
230                 /*
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.
234                  */
235                 Hook::callAll('authenticate', $addon_auth);
236
237                 try {
238                         if ($addon_auth['authenticated']) {
239                                 $record = $addon_auth['user_record'];
240
241                                 if (empty($record)) {
242                                         throw new Exception($this->l10n->t('Login failed.'));
243                                 }
244                         } else {
245                                 $record = $this->dba->selectFirst(
246                                         'user',
247                                         [],
248                                         ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
249                                 );
250                         }
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();
255                 }
256
257                 if (!$remember) {
258                         $this->cookie->clear();
259                 }
260
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());
264
265                 $openid_identity = $this->session->get('openid_identity');
266                 $openid_server   = $this->session->get('openid_server');
267
268                 if (!empty($openid_identity) || !empty($openid_server)) {
269                         $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
270                 }
271
272                 $this->setForUser($a, $record, true, true);
273
274                 $return_path = $this->session->get('return_path', '');
275                 $this->session->remove('return_path');
276
277                 $this->baseUrl->redirect($return_path);
278         }
279
280         /**
281          * @brief Sets the provided user's authenticated session
282          *
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
288          *
289          * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
290          * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
291          */
292         public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
293         {
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'
303                 ]);
304
305                 Session::setVisitorsContacts();
306
307                 $member_since = strtotime($user_record['register_date']);
308                 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
309
310                 if (strlen($user_record['timezone'])) {
311                         date_default_timezone_set($user_record['timezone']);
312                         $a->timezone = $user_record['timezone'];
313                 }
314
315                 $masterUid = $user_record['uid'];
316
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'];
321                         }
322                 }
323
324                 $a->identities = User::identities($masterUid);
325
326                 if ($login_initial) {
327                         $this->logger->info('auth_identities: ' . print_r($a->identities, true));
328                 }
329
330                 if ($login_refresh) {
331                         $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
332                 }
333
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);
339                 }
340
341                 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
342
343                 if ($login_initial || $login_refresh) {
344                         $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
345
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]);
349                 }
350
351                 if ($login_initial) {
352                         /*
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.
357                          */;
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');
362                         }
363                 }
364
365                 $this->twoFactorCheck($user_record['uid'], $a);
366
367                 if ($interactive) {
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');
372                         } else {
373                                 info($this->l10n->t("Welcome back %s", $user_record['username']));
374                         }
375                 }
376
377                 $a->user = $user_record;
378
379                 if ($login_initial) {
380                         Hook::callAll('logged_in', $a->user);
381
382                         if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
383                                 $this->baseUrl->redirect($this->session->get('return_path'));
384                         }
385                 }
386         }
387
388         /**
389          * @param int $uid The User Identified
390          * @param App $a   The Friendica Application context
391          *
392          * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
393          */
394         private function twoFactorCheck(int $uid, App $a)
395         {
396                 // Check user setting, if 2FA disabled return
397                 if (!PConfig::get($uid, '2fa', 'verified')) {
398                         return;
399                 }
400
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'])) {
403                         return;
404                 }
405
406                 // Case 1: 2FA session present and valid: return
407                 if ($this->session->get('2fa')) {
408                         return;
409                 }
410
411                 // Case 2: No valid 2FA session: redirect to code verification page
412                 if ($this->mode->isAjax()) {
413                         throw new HTTPException\ForbiddenException();
414                 } else {
415                         $this->baseUrl->redirect('2fa');
416                 }
417         }
418 }