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