]> git.mxchange.org Git - friendica.git/blob - src/Module/Magic.php
old boot.php functions replaced in src/module
[friendica.git] / src / Module / Magic.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;
23
24 use Friendica\App;
25 use Friendica\BaseModule;
26 use Friendica\Core\L10n;
27 use Friendica\Core\Session;
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
54         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 = [])
55         {
56                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
57
58                 $this->app        = $app;
59                 $this->dba        = $dba;
60                 $this->httpClient = $httpClient;
61         }
62
63         protected function rawContent(array $request = [])
64         {
65                 $this->logger->info('magic module: invoked');
66
67                 $this->logger->debug('args', ['request' => $_REQUEST]);
68
69                 $addr = $_REQUEST['addr'] ?? '';
70                 $dest = $_REQUEST['dest'] ?? '';
71                 $owa  = (!empty($_REQUEST['owa'])  ? intval($_REQUEST['owa'])  : 0);
72                 $cid  = 0;
73
74                 if (!empty($addr)) {
75                         $cid = Contact::getIdForURL($addr);
76                 } elseif (!empty($dest)) {
77                         $cid = Contact::getIdForURL($dest);
78                 }
79
80                 if (!$cid) {
81                         $this->logger->info('No contact record found', $_REQUEST);
82                         // @TODO Finding a more elegant possibility to redirect to either internal or external URL
83                         $this->app->redirect($dest);
84                 }
85                 $contact = $this->dba->selectFirst('contact', ['id', 'nurl', 'url'], ['id' => $cid]);
86
87                 // Redirect if the contact is already authenticated on this site.
88                 if ($this->app->getContactId() && strpos($contact['nurl'], Strings::normaliseLink($this->baseUrl->get())) !== false) {
89                         $this->logger->info('Contact is already authenticated');
90                         System::externalRedirect($dest);
91                 }
92
93                 // OpenWebAuth
94                 if (Session::getLocalUser() && $owa) {
95                         $user = User::getById(Session::getLocalUser());
96
97                         // Extract the basepath
98                         // NOTE: we need another solution because this does only work
99                         // for friendica contacts :-/ . We should have the basepath
100                         // of a contact also in the contact table.
101                         $exp = explode('/profile/', $contact['url']);
102                         $basepath = $exp[0];
103
104                         $header = [
105                                 'Accept'                  => ['application/x-dfrn+json', 'application/x-zot+json'],
106                                 'X-Open-Web-Auth' => [Strings::getRandomHex()],
107                         ];
108
109                         // Create a header that is signed with the local users private key.
110                         $header = HTTPSignature::createSig(
111                                 $header,
112                                 $user['prvkey'],
113                                 'acct:' . $user['nickname'] . '@' . $this->baseUrl->getHostname() . ($this->baseUrl->getUrlPath() ? '/' . $this->baseUrl->getUrlPath() : '')
114                         );
115
116                         // Try to get an authentication token from the other instance.
117                         $curlResult = $this->httpClient->get($basepath . '/owa', HttpClientAccept::DEFAULT, [HttpClientOptions::HEADERS => $header]);
118
119                         if ($curlResult->isSuccess()) {
120                                 $j = json_decode($curlResult->getBody(), true);
121
122                                 if ($j['success']) {
123                                         $token = '';
124                                         if ($j['encrypted_token']) {
125                                                 // The token is encrypted. If the local user is really the one the other instance
126                                                 // thinks he/she is, the token can be decrypted with the local users public key.
127                                                 openssl_private_decrypt(Strings::base64UrlDecode($j['encrypted_token']), $token, $user['prvkey']);
128                                         } else {
129                                                 $token = $j['token'];
130                                         }
131                                         $args = (strpbrk($dest, '?&') ? '&' : '?') . 'owt=' . $token;
132
133                                         $this->logger->info('Redirecting', ['path' => $dest . $args]);
134                                         System::externalRedirect($dest . $args);
135                                 }
136                         }
137                         System::externalRedirect($dest);
138                 }
139
140                 // @TODO Finding a more elegant possibility to redirect to either internal or external URL
141                 $this->app->redirect($dest);
142         }
143 }