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