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;
26 use Friendica\BaseModule;
27 use Friendica\Core\L10n;
28 use Friendica\Core\Session\Capability\IHandleUserSessions;
29 use Friendica\Core\System;
30 use Friendica\Database\Database;
31 use Friendica\Model\Contact;
32 use Friendica\Model\GServer;
33 use Friendica\Model\User;
34 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
35 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
36 use Friendica\Util\HTTPSignature;
37 use Friendica\Util\Profiler;
38 use Friendica\Util\Strings;
39 use GuzzleHttp\Psr7\Uri;
40 use Psr\Log\LoggerInterface;
43 * Magic Auth (remote authentication) module.
45 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Magic.php
47 class Magic extends BaseModule
53 /** @var ICanSendHttpRequests */
54 protected $httpClient;
55 /** @var IHandleUserSessions */
56 protected $userSession;
58 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 = [])
60 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
64 $this->httpClient = $httpClient;
65 $this->userSession = $userSession;
68 protected function rawContent(array $request = [])
70 if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
71 $this->logger->debug('Got a HEAD request');
75 $this->logger->debug('Invoked', ['request' => $request]);
77 $addr = $request['addr'] ?? '';
78 $dest = $request['dest'] ?? '';
79 $bdest = $request['bdest'] ?? '';
80 $owa = intval($request['owa'] ?? 0);
82 // bdest is preferred as it is hex-encoded and can survive url rewrite and argument parsing
84 $dest = hex2bin($bdest);
85 $this->logger->debug('bdest detected', ['dest' => $dest]);
88 $target = $dest ?: $addr;
91 $contact = Contact::getByURL($addr ?: $dest);
94 if (empty($contact)) {
96 $this->logger->info('No contact record found, no oWA, redirecting to destination.', ['request' => $request, 'server' => $_SERVER, 'dest' => $dest]);
97 $this->app->redirect($dest);
100 // Redirect if the contact is already authenticated on this site.
101 if ($this->app->getContactId() && strpos($contact['nurl'], Strings::normaliseLink($this->baseUrl)) !== false) {
102 $this->logger->info('Contact is already authenticated, redirecting to destination.', ['dest' => $dest]);
103 System::externalRedirect($dest);
106 $this->logger->debug('Contact found', ['url' => $contact['url']]);
109 if (!$this->userSession->getLocalUserId() || !$owa) {
110 $this->logger->notice('Not logged in or not OWA, redirecting to destination.', ['uid' => $this->userSession->getLocalUserId(), 'owa' => $owa, 'dest' => $dest]);
111 $this->app->redirect($dest);
115 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
117 if (!empty($contact['gsid'])) {
118 $gserver = $this->dba->selectFirst('gserver', ['url'], ['id' => $contact['gsid']]);
119 if (empty($gserver)) {
120 $this->logger->notice('Server not found, redirecting to destination.', ['gsid' => $contact['gsid'], 'dest' => $dest]);
121 System::externalRedirect($dest);
124 $basepath = $gserver['url'];
125 } elseif (GServer::check($target)) {
126 $basepath = (string)GServer::cleanUri(new Uri($target));
128 $this->logger->notice('The target is not a server path, redirecting to destination.', ['target' => $target]);
129 System::externalRedirect($dest);
133 'Accept' => 'application/x-dfrn+json, application/x-zot+json',
134 'X-Open-Web-Auth' => Strings::getRandomHex()
137 // Create a header that is signed with the local users private key.
138 $header = HTTPSignature::createSig(
141 'acct:' . $owner['addr']
144 $this->logger->info('Fetch from remote system', ['basepath' => $basepath, 'headers' => $header]);
146 // Try to get an authentication token from the other instance.
148 $curlResult = $this->httpClient->request('get', $basepath . '/owa', [HttpClientOptions::HEADERS => $header]);
149 } catch (Exception $exception) {
150 $this->logger->notice('URL is invalid, redirecting to destination.', ['url' => $basepath, 'error' => $exception, 'dest' => $dest]);
151 System::externalRedirect($dest);
153 if (!$curlResult->isSuccess()) {
154 $this->logger->notice('OWA request failed, redirecting to destination.', ['returncode' => $curlResult->getReturnCode(), 'dest' => $dest]);
155 System::externalRedirect($dest);
158 $j = json_decode($curlResult->getBody(), true);
159 if (empty($j) || !$j['success']) {
160 $this->logger->notice('Invalid JSON, redirecting to destination.', ['json' => $j, 'dest' => $dest]);
161 $this->app->redirect($dest);
164 if ($j['encrypted_token']) {
165 // The token is encrypted. If the local user is really the one the other instance
166 // thinks they is, the token can be decrypted with the local users public key.
168 openssl_private_decrypt(Strings::base64UrlDecode($j['encrypted_token']), $token, $owner['prvkey']);
170 $token = $j['token'];
172 $args = (strpbrk($dest, '?&') ? '&' : '?') . 'owt=' . $token;
174 $this->logger->debug('Redirecting', ['path' => $dest . $args]);
175 System::externalRedirect($dest . $args);