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