]> git.mxchange.org Git - friendica.git/blob - src/Module/Magic.php
Introduce `Response` for Modules to create a testable way for module responses
[friendica.git] / src / Module / Magic.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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;
23
24 use Friendica\App;
25 use Friendica\BaseModule;
26 use Friendica\Core\L10n;
27 use Friendica\Core\System;
28 use Friendica\Database\Database;
29 use Friendica\Model\Contact;
30 use Friendica\Model\User;
31 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
32 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
33 use Friendica\Util\HTTPSignature;
34 use Friendica\Util\Profiler;
35 use Friendica\Util\Strings;
36 use Psr\Log\LoggerInterface;
37
38 /**
39  * Magic Auth (remote authentication) module.
40  *
41  * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Magic.php
42  */
43 class Magic extends BaseModule
44 {
45         /** @var App */
46         protected $app;
47         /** @var Database */
48         protected $dba;
49         /** @var ICanSendHttpRequests */
50         protected $httpClient;
51
52         public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, Database $dba, ICanSendHttpRequests $httpClient, array $server, array $parameters = [])
53         {
54                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
55
56                 $this->app        = $app;
57                 $this->dba        = $dba;
58                 $this->httpClient = $httpClient;
59         }
60
61         protected function rawContent(array $request = [])
62         {
63                 $this->logger->info('magic module: invoked');
64
65                 $this->logger->debug('args', ['request' => $_REQUEST]);
66
67                 $addr = $_REQUEST['addr'] ?? '';
68                 $dest = $_REQUEST['dest'] ?? '';
69                 $owa  = (!empty($_REQUEST['owa'])  ? intval($_REQUEST['owa'])  : 0);
70                 $cid  = 0;
71
72                 if (!empty($addr)) {
73                         $cid = Contact::getIdForURL($addr);
74                 } elseif (!empty($dest)) {
75                         $cid = Contact::getIdForURL($dest);
76                 }
77
78                 if (!$cid) {
79                         $this->logger->info('No contact record found', $_REQUEST);
80                         // @TODO Finding a more elegant possibility to redirect to either internal or external URL
81                         $this->app->redirect($dest);
82                 }
83                 $contact = $this->dba->selectFirst('contact', ['id', 'nurl', 'url'], ['id' => $cid]);
84
85                 // Redirect if the contact is already authenticated on this site.
86                 if ($this->app->getContactId() && strpos($contact['nurl'], Strings::normaliseLink($this->baseUrl->get())) !== false) {
87                         $this->logger->info('Contact is already authenticated');
88                         System::externalRedirect($dest);
89                 }
90
91                 // OpenWebAuth
92                 if (local_user() && $owa) {
93                         $user = User::getById(local_user());
94
95                         // Extract the basepath
96                         // NOTE: we need another solution because this does only work
97                         // for friendica contacts :-/ . We should have the basepath
98                         // of a contact also in the contact table.
99                         $exp = explode('/profile/', $contact['url']);
100                         $basepath = $exp[0];
101
102                         $header = [
103                                 'Accept'                  => ['application/x-dfrn+json', 'application/x-zot+json'],
104                                 'X-Open-Web-Auth' => [Strings::getRandomHex()],
105                         ];
106
107                         // Create a header that is signed with the local users private key.
108                         $header = HTTPSignature::createSig(
109                                 $header,
110                                 $user['prvkey'],
111                                 'acct:' . $user['nickname'] . '@' . $this->baseUrl->getHostname() . ($this->baseUrl->getUrlPath() ? '/' . $this->baseUrl->getUrlPath() : '')
112                         );
113
114                         // Try to get an authentication token from the other instance.
115                         $curlResult = $this->httpClient->get($basepath . '/owa', [HttpClientOptions::HEADERS => $header]);
116
117                         if ($curlResult->isSuccess()) {
118                                 $j = json_decode($curlResult->getBody(), true);
119
120                                 if ($j['success']) {
121                                         $token = '';
122                                         if ($j['encrypted_token']) {
123                                                 // The token is encrypted. If the local user is really the one the other instance
124                                                 // thinks he/she is, the token can be decrypted with the local users public key.
125                                                 openssl_private_decrypt(Strings::base64UrlDecode($j['encrypted_token']), $token, $user['prvkey']);
126                                         } else {
127                                                 $token = $j['token'];
128                                         }
129                                         $args = (strpbrk($dest, '?&') ? '&' : '?') . 'owt=' . $token;
130
131                                         $this->logger->info('Redirecting', ['path' => $dest . $args]);
132                                         System::externalRedirect($dest . $args);
133                                 }
134                         }
135                         System::externalRedirect($dest);
136                 }
137
138                 // @TODO Finding a more elegant possibility to redirect to either internal or external URL
139                 $this->app->redirect($dest);
140         }
141 }