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