]> git.mxchange.org Git - friendica.git/blob - src/Module/Security/TwoFactor/Trust.php
1f5fb7418f5b24c1885ed72a487137a981df29e8
[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\Capability\IHandleSessions;
29 use Friendica\Model\User;
30 use Friendica\Model\User\Cookie;
31 use Friendica\Module\Response;
32 use Friendica\Network\HTTPException\FoundException;
33 use Friendica\Network\HTTPException\MovedPermanentlyException;
34 use Friendica\Network\HTTPException\TemporaryRedirectException;
35 use Friendica\Security\Authentication;
36 use Friendica\Security\TwoFactor\Exception\TrustedBrowserNotFoundException;
37 use Friendica\Security\TwoFactor\Exception\TrustedBrowserPersistenceException;
38 use Friendica\Util\Profiler;
39 use Friendica\Security\TwoFactor;
40 use Psr\Log\LoggerInterface;
41
42 /**
43  * Page 2: Trust Browser dialog
44  *
45  * @package Friendica\Module\TwoFactor
46  */
47 class Trust extends BaseModule
48 {
49         /** @var App  */
50         protected $app;
51         /** @var Authentication  */
52         protected $auth;
53         /** @var IHandleSessions  */
54         protected $session;
55         /** @var Cookie  */
56         protected $cookie;
57         /** @var TwoFactor\Factory\TrustedBrowser  */
58         protected $trustedBrowserFactory;
59         /** @var TwoFactor\Repository\TrustedBrowser  */
60         protected $trustedBrowserRepository;
61
62         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 = [])
63         {
64                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
65
66                 $this->app                      = $app;
67                 $this->auth                     = $auth;
68                 $this->session                  = $session;
69                 $this->cookie                   = $cookie;
70                 $this->trustedBrowserFactory    = $trustedBrowserFactory;
71                 $this->trustedBrowserRepository = $trustedBrowserRepositoy;
72         }
73
74         protected function post(array $request = [])
75         {
76                 if (!local_user() || !$this->session->get('2fa')) {
77                         $this->logger->info('Invalid call', ['request' => $request]);
78                         return;
79                 }
80
81                 $action = $request['action'] ?? '';
82
83                 if (!empty($action)) {
84                         self::checkFormSecurityTokenRedirectOnError('2fa', 'twofactor_trust');
85
86                         switch ($action) {
87                                 case 'trust':
88                                 case 'dont_trust':
89                                         $trustedBrowser = $this->trustedBrowserFactory->createForUserWithUserAgent(local_user(), $this->server['HTTP_USER_AGENT'], $action === 'trust');
90                                         try {
91                                                 $this->trustedBrowserRepository->save($trustedBrowser);
92
93                                                 // The string is sent to the browser to be sent back with each request
94                                                 if (!$this->cookie->set('2fa_cookie_hash', $trustedBrowser->cookie_hash)) {
95                                                         notice($this->t('Couldn\'t save browser to Cookie.'));
96                                                 };
97                                         } catch (TrustedBrowserPersistenceException $exception) {
98                                                 $this->logger->warning('Unexpected error when saving the trusted browser.', ['trustedBrowser' => $trustedBrowser, 'exception' => $exception]);
99                                         }
100                                         break;
101                         }
102
103                         try {
104                                 $this->auth->setForUser($this->app, User::getById($this->app->getLoggedInUserId()), true, true);
105                                 $this->baseUrl->redirect($this->session->pop('return_path', ''));
106                         } catch (FoundException | TemporaryRedirectException | MovedPermanentlyException $e) {
107                                 // exception wanted!
108                                 throw $e;
109                         } catch (\Exception $e) {
110                                 $this->logger->warning('Unexpected error during authentication.', ['user' => $this->app->getLoggedInUserId(), 'exception' => $exception]);
111                         }
112                 }
113         }
114
115         protected function content(array $request = []): string
116         {
117                 if (!local_user() || !$this->session->get('2fa')) {
118                         $this->baseUrl->redirect();
119                 }
120
121                 if ($this->cookie->get('2fa_cookie_hash')) {
122                         try {
123                                 $trustedBrowser = $this->trustedBrowserRepository->selectOneByHash($this->cookie->get('2fa_cookie_hash'));
124                                 if (!$trustedBrowser->trusted) {
125                                         $this->auth->setForUser($this->app, User::getById($this->app->getLoggedInUserId()), true, true);
126                                         $this->baseUrl->redirect($this->session->pop('return_path', ''));
127                                 }
128                         } catch (TrustedBrowserNotFoundException $exception) {
129                                 $this->logger->notice('Trusted Browser of the cookie not found.', ['cookie_hash' => $this->cookie->get('trusted'), 'uid' => $this->app->getLoggedInUserId(), 'exception' => $exception]);
130                         } catch (TrustedBrowserPersistenceException $exception) {
131                                 $this->logger->warning('Unexpected persistence exception.', ['cookie_hash' => $this->cookie->get('trusted'), 'uid' => $this->app->getLoggedInUserId(), 'exception' => $exception]);
132                         } catch (\Exception $exception) {
133                                 $this->logger->warning('Unexpected exception.', ['cookie_hash' => $this->cookie->get('trusted'), 'uid' => $this->app->getLoggedInUserId(), 'exception' => $exception]);
134                         }
135                 }
136
137                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('twofactor/trust.tpl'), [
138                         '$form_security_token' => self::getFormSecurityToken('twofactor_trust'),
139
140                         '$title'            => $this->t('Trust this browser?'),
141                         '$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>'),
142                         '$not_now_label'    => $this->t('Not now'),
143                         '$dont_trust_label' => $this->t('Don\'t trust'),
144                         '$trust_label'      => $this->t('Trust'),
145                 ]);
146         }
147 }