3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Module;
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;
41 * Magic Auth (remote authentication) module.
43 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Magic.php
45 class Magic extends BaseModule
51 /** @var ICanSendHttpRequests */
52 protected $httpClient;
53 /** @var IHandleUserSessions */
54 protected $userSession;
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 = [])
58 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
62 $this->httpClient = $httpClient;
63 $this->userSession = $userSession;
66 protected function rawContent(array $request = [])
68 $this->logger->info('magic module: invoked');
70 $this->logger->debug('args', ['request' => $_REQUEST]);
72 $addr = $_REQUEST['addr'] ?? '';
73 $dest = $_REQUEST['dest'] ?? '';
74 $owa = (!empty($_REQUEST['owa']) ? intval($_REQUEST['owa']) : 0);
78 $cid = Contact::getIdForURL($addr);
79 } elseif (!empty($dest)) {
80 $cid = Contact::getIdForURL($dest);
84 $this->logger->info('No contact record found', $_REQUEST);
85 // @TODO Finding a more elegant possibility to redirect to either internal or external URL
86 $this->app->redirect($dest);
88 $contact = $this->dba->selectFirst('contact', ['id', 'nurl', 'url'], ['id' => $cid]);
90 // Redirect if the contact is already authenticated on this site.
91 if ($this->app->getContactId() && strpos($contact['nurl'], Strings::normaliseLink($this->baseUrl->get())) !== false) {
92 $this->logger->info('Contact is already authenticated');
93 System::externalRedirect($dest);
97 if ($this->userSession->getLocalUserId() && $owa) {
98 $user = User::getById($this->userSession->getLocalUserId());
100 // Extract the basepath
101 // NOTE: we need another solution because this does only work
102 // for friendica contacts :-/ . We should have the basepath
103 // of a contact also in the contact table.
104 $exp = explode('/profile/', $contact['url']);
108 'Accept' => ['application/x-dfrn+json', 'application/x-zot+json'],
109 'X-Open-Web-Auth' => [Strings::getRandomHex()],
112 // Create a header that is signed with the local users private key.
113 $header = HTTPSignature::createSig(
116 'acct:' . $user['nickname'] . '@' . $this->baseUrl->getHostname() . ($this->baseUrl->getUrlPath() ? '/' . $this->baseUrl->getUrlPath() : '')
119 // Try to get an authentication token from the other instance.
120 $curlResult = $this->httpClient->get($basepath . '/owa', HttpClientAccept::DEFAULT, [HttpClientOptions::HEADERS => $header]);
122 if ($curlResult->isSuccess()) {
123 $j = json_decode($curlResult->getBody(), true);
127 if ($j['encrypted_token']) {
128 // The token is encrypted. If the local user is really the one the other instance
129 // thinks he/she is, the token can be decrypted with the local users public key.
130 openssl_private_decrypt(Strings::base64UrlDecode($j['encrypted_token']), $token, $user['prvkey']);
132 $token = $j['token'];
134 $args = (strpbrk($dest, '?&') ? '&' : '?') . 'owt=' . $token;
136 $this->logger->info('Redirecting', ['path' => $dest . $args]);
137 System::externalRedirect($dest . $args);
140 System::externalRedirect($dest);
143 // @TODO Finding a more elegant possibility to redirect to either internal or external URL
144 $this->app->redirect($dest);