]> git.mxchange.org Git - friendica.git/blob - src/Module/Security/TwoFactor/Trust.php
3b64056c54c100174620dfff5417872a4b966fb1
[friendica.git] / src / Module / Security / TwoFactor / Trust.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module\Security\TwoFactor;
23
24 use Friendica\App;
25 use Friendica\BaseModule;
26 use Friendica\Core\L10n;
27 use Friendica\Core\Renderer;
28 use Friendica\Core\Session;
29 use Friendica\Core\Session\Capability\IHandleSessions;
30 use Friendica\DI;
31 use Friendica\Model\User;
32 use Friendica\Model\User\Cookie;
33 use Friendica\Module\Response;
34 use Friendica\Network\HTTPException\FoundException;
35 use Friendica\Network\HTTPException\MovedPermanentlyException;
36 use Friendica\Network\HTTPException\TemporaryRedirectException;
37 use Friendica\Security\Authentication;
38 use Friendica\Security\TwoFactor\Exception\TrustedBrowserNotFoundException;
39 use Friendica\Security\TwoFactor\Exception\TrustedBrowserPersistenceException;
40 use Friendica\Util\Profiler;
41 use Friendica\Security\TwoFactor;
42 use Psr\Log\LoggerInterface;
43
44 /**
45  * Page 2: Trust Browser dialog
46  *
47  * @package Friendica\Module\TwoFactor
48  */
49 class Trust extends BaseModule
50 {
51         /** @var App  */
52         protected $app;
53         /** @var Authentication  */
54         protected $auth;
55         /** @var IHandleSessions  */
56         protected $session;
57         /** @var Cookie  */
58         protected $cookie;
59         /** @var TwoFactor\Factory\TrustedBrowser  */
60         protected $trustedBrowserFactory;
61         /** @var TwoFactor\Repository\TrustedBrowser  */
62         protected $trustedBrowserRepository;
63
64         public function __construct(App $app, Authentication $auth, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, IHandleSessions $session, Cookie $cookie, TwoFactor\Factory\TrustedBrowser $trustedBrowserFactory, TwoFactor\Repository\TrustedBrowser $trustedBrowserRepositoy, Response $response, array $server, array $parameters = [])
65         {
66                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
67
68                 $this->app                      = $app;
69                 $this->auth                     = $auth;
70                 $this->session                  = $session;
71                 $this->cookie                   = $cookie;
72                 $this->trustedBrowserFactory    = $trustedBrowserFactory;
73                 $this->trustedBrowserRepository = $trustedBrowserRepositoy;
74         }
75
76         protected function post(array $request = [])
77         {
78                 if (!Session::getLocalUser() || !$this->session->get('2fa')) {
79                         $this->logger->info('Invalid call', ['request' => $request]);
80                         return;
81                 }
82
83                 $action = $request['action'] ?? '';
84
85                 if (!empty($action)) {
86                         self::checkFormSecurityTokenRedirectOnError('2fa', 'twofactor_trust');
87
88                         switch ($action) {
89                                 case 'trust':
90                                 case 'dont_trust':
91                                         $trustedBrowser = $this->trustedBrowserFactory->createForUserWithUserAgent(Session::getLocalUser(), $this->server['HTTP_USER_AGENT'], $action === 'trust');
92                                         try {
93                                                 $this->trustedBrowserRepository->save($trustedBrowser);
94
95                                                 // The string is sent to the browser to be sent back with each request
96                                                 if (!$this->cookie->set('2fa_cookie_hash', $trustedBrowser->cookie_hash)) {
97                                                         DI::sysmsg()->addNotice($this->t('Couldn\'t save browser to Cookie.'));
98                                                 };
99                                         } catch (TrustedBrowserPersistenceException $exception) {
100                                                 $this->logger->warning('Unexpected error when saving the trusted browser.', ['trustedBrowser' => $trustedBrowser, 'exception' => $exception]);
101                                         }
102                                         break;
103                         }
104
105                         try {
106                                 $this->auth->setForUser($this->app, User::getById($this->app->getLoggedInUserId()), true, true);
107                                 $this->baseUrl->redirect($this->session->pop('return_path', ''));
108                         } catch (FoundException | TemporaryRedirectException | MovedPermanentlyException $e) {
109                                 // exception wanted!
110                                 throw $e;
111                         } catch (\Exception $e) {
112                                 $this->logger->warning('Unexpected error during authentication.', ['user' => $this->app->getLoggedInUserId(), 'exception' => $exception]);
113                         }
114                 }
115         }
116
117         protected function content(array $request = []): string
118         {
119                 if (!Session::getLocalUser() || !$this->session->get('2fa')) {
120                         $this->baseUrl->redirect();
121                 }
122
123                 if ($this->cookie->get('2fa_cookie_hash')) {
124                         try {
125                                 $trustedBrowser = $this->trustedBrowserRepository->selectOneByHash($this->cookie->get('2fa_cookie_hash'));
126                                 if (!$trustedBrowser->trusted) {
127                                         $this->auth->setForUser($this->app, User::getById($this->app->getLoggedInUserId()), true, true);
128                                         $this->baseUrl->redirect($this->session->pop('return_path', ''));
129                                 }
130                         } catch (TrustedBrowserNotFoundException $exception) {
131                                 $this->logger->notice('Trusted Browser of the cookie not found.', ['cookie_hash' => $this->cookie->get('trusted'), 'uid' => $this->app->getLoggedInUserId(), 'exception' => $exception]);
132                         } catch (TrustedBrowserPersistenceException $exception) {
133                                 $this->logger->warning('Unexpected persistence exception.', ['cookie_hash' => $this->cookie->get('trusted'), 'uid' => $this->app->getLoggedInUserId(), 'exception' => $exception]);
134                         } catch (\Exception $exception) {
135                                 $this->logger->warning('Unexpected exception.', ['cookie_hash' => $this->cookie->get('trusted'), 'uid' => $this->app->getLoggedInUserId(), 'exception' => $exception]);
136                         }
137                 }
138
139                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('twofactor/trust.tpl'), [
140                         '$form_security_token' => self::getFormSecurityToken('twofactor_trust'),
141
142                         '$title'            => $this->t('Trust this browser?'),
143                         '$message'          => $this->t('<p>If you choose to trust this browser, you will not be asked for a verification code the next time you sign in.</p>'),
144                         '$not_now_label'    => $this->t('Not now'),
145                         '$dont_trust_label' => $this->t('Don\'t trust'),
146                         '$trust_label'      => $this->t('Trust'),
147                 ]);
148         }
149 }