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