]> git.mxchange.org Git - friendica.git/blob - src/Module/Magic.php
0f710b6a0ba46f8b003e2d42ff00508b580b6c09
[friendica.git] / src / Module / Magic.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Session\Capability\IHandleUserSessions;
28 use Friendica\Core\System;
29 use Friendica\Database\Database;
30 use Friendica\Model\Contact;
31 use Friendica\Model\User;
32 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
33 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
34 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
35 use Friendica\Util\HTTPSignature;
36 use Friendica\Util\Profiler;
37 use Friendica\Util\Strings;
38 use Psr\Log\LoggerInterface;
39
40 /**
41  * Magic Auth (remote authentication) module.
42  *
43  * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Magic.php
44  */
45 class Magic extends BaseModule
46 {
47         /** @var App */
48         protected $app;
49         /** @var Database */
50         protected $dba;
51         /** @var ICanSendHttpRequests */
52         protected $httpClient;
53         /** @var IHandleUserSessions */
54         protected $userSession;
55
56         public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, Database $dba, ICanSendHttpRequests $httpClient, IHandleUserSessions $userSession, $server, array $parameters = [])
57         {
58                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
59
60                 $this->app         = $app;
61                 $this->dba         = $dba;
62                 $this->httpClient  = $httpClient;
63                 $this->userSession = $userSession;
64         }
65
66         protected function rawContent(array $request = [])
67         {
68                 $this->logger->info('magic module: invoked');
69
70                 $this->logger->debug('args', ['request' => $_REQUEST]);
71
72                 $addr  = $request['addr'] ?? '';
73                 $dest  = $request['dest'] ?? '';
74                 $bdest = $request['bdest'] ?? '';
75                 $owa   = intval($request['owa'] ?? 0);
76                 $cid  = 0;
77
78                 // bdest is preferred as it is hex-encoded and can survive url rewrite and argument parsing
79                 if (!empty($bdest)) {
80                         $dest = hex2bin($bdest);
81                         $this->logger->info('bdest detected. ', ['dest' => $dest]);
82                 }
83                 if (!empty($addr)) {
84                         $cid = Contact::getIdForURL($addr);
85                 } elseif (!empty($dest)) {
86                         $cid = Contact::getIdForURL($dest);
87                 }
88                 $this->logger->info('Contact ID: ', ['cid' => $cid]);
89                 
90                 $contact = false;
91                 if (!$cid) {
92                         $this->logger->info('No contact record found', $_REQUEST);
93
94                         if (!$owa) {
95                                 // @TODO Finding a more elegant possibility to redirect to either internal or external URL
96                                 $this->app->redirect($dest);
97                         }
98                 } else {
99                         $contact = $this->dba->selectFirst('contact', ['id', 'nurl', 'url'], ['id' => $cid]);
100
101                         // Redirect if the contact is already authenticated on this site.
102                         if ($this->app->getContactId() && strpos($contact['nurl'], Strings::normaliseLink($this->baseUrl)) !== false) {
103                                 $this->logger->info('Contact is already authenticated');
104                                 System::externalRedirect($dest);
105                         }
106
107                         $this->logger->info('Contact URL: ', ['url' => $contact['url']]);
108                 }
109
110                 // OpenWebAuth
111                 if ($this->userSession->getLocalUserId() && $owa) {
112                         $this->logger->info('Checking OWA now');
113                         $user = User::getById($this->userSession->getLocalUserId());
114
115                         $basepath = false;
116                         if (!empty($contact)) {
117                                 $this->logger->info('Contact found - trying friendica style basepath extraction');
118                                 // Extract the basepath
119                                 // NOTE: we need another solution because this does only work
120                                 // for friendica contacts :-/ . We should have the basepath
121                                 // of a contact also in the contact table.
122                                 $contact_url = $contact['url'];
123                                 if (!(strpos($contact_url, '/profile/') === false)) {
124                                         $exp = explode('/profile/', $contact['url']);
125                                         $basepath = $exp[0];
126                                         $this->logger->info('Basepath: ', ['basepath' => $basepath]);
127                                 } else {
128                                         $this->logger->info('Not possible to extract basepath in friendica style');
129                                 }
130                         }
131                         if (!$basepath) {
132                                 // For the rest of the OpenWebAuth-enabled Fediverse
133                                 $parsed = parse_url($dest);
134                                 $this->logger->info('Parsed URL: ', ['parsed URL' => $parsed]);
135                                 if (!$parsed) {
136                                         System::externalRedirect($dest);
137                                 }
138                                 $basepath = $parsed['scheme'] . '://' . $parsed['host'] . (isset($parsed['port']) ? ':' . $parsed['port'] : '');
139                         }
140
141                         $accept_headers = ['application/x-dfrn+json', 'application/x-zot+json'];
142                         $header = [
143                                 'Accept'         => $accept_headers,
144                                 'X-Open-Web-Auth' => [Strings::getRandomHex()],
145                         ];
146
147                         // Create a header that is signed with the local users private key.
148                         $header = HTTPSignature::createSig(
149                                 $header,
150                                 $user['prvkey'],
151                                 'acct:' . $user['nickname'] . '@' . $this->baseUrl->getHost() . ($this->baseUrl->getPath() ? '/' . $this->baseUrl->getPath() : '')
152                         );
153
154                         $this->logger->info('Headers: ', ['headers' => $header]);
155
156                         // Try to get an authentication token from the other instance.
157                         $curlResult = $this->httpClient->get($basepath . '/owa', HttpClientAccept::DEFAULT, [HttpClientOptions::HEADERS => $header, HttpClientOptions::ACCEPT_CONTENT => $accept_headers]);
158
159                         if ($curlResult->isSuccess()) {
160                                 $j = json_decode($curlResult->getBody(), true);
161                                 $this->logger->info('Curl result body: ', ['body' => $j]);
162
163                                 if ($j['success']) {
164                                         $token = '';
165                                         if ($j['encrypted_token']) {
166                                                 // The token is encrypted. If the local user is really the one the other instance
167                                                 // thinks he/she is, the token can be decrypted with the local users public key.
168                                                 openssl_private_decrypt(Strings::base64UrlDecode($j['encrypted_token']), $token, $user['prvkey']);
169                                         } else {
170                                                 $token = $j['token'];
171                                         }
172                                         $args = (strpbrk($dest, '?&') ? '&' : '?') . 'owt=' . $token;
173
174                                         $this->logger->info('Redirecting', ['path' => $dest . $args]);
175                                         System::externalRedirect($dest . $args);
176                                 }
177                         }
178                         System::externalRedirect($dest);
179                 }
180
181                 // @TODO Finding a more elegant possibility to redirect to either internal or external URL
182                 $this->app->redirect($dest);
183         }
184 }