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\Contact;
24 use Friendica\Core\L10n;
26 use Friendica\Core\Session\Capability\IHandleUserSessions;
27 use Friendica\Database\Database;
28 use Friendica\Model\Contact;
29 use Friendica\Module\Response;
30 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
31 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
32 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
33 use Friendica\Network\HTTPException;
34 use Friendica\Util\Profiler;
35 use Friendica\Util\Strings;
36 use Psr\Log\LoggerInterface;
38 class Redir extends \Friendica\BaseModule
40 /** @var IHandleUserSessions */
46 /** @var ICanSendHttpRequests */
49 public function __construct(ICanSendHttpRequests $httpClient, App $app, Database $database, IHandleUserSessions $session, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
51 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
53 $this->session = $session;
54 $this->database = $database;
56 $this->httpClient = $httpClient;
59 protected function rawContent(array $request = [])
61 if (!$this->session->isAuthenticated()) {
62 throw new HTTPException\ForbiddenException($this->t('Access denied.'));
65 $url = $request['url'] ?? '';
67 $cid = $this->parameters['id'] ?? 0;
69 // Try magic auth before the legacy stuff
70 $this->magic($cid, $url);
72 $this->legacy($cid, $url);
79 * @throws HTTPException\ForbiddenException
80 * @throws HTTPException\InternalServerErrorException
81 * @throws HTTPException\NotFoundException
82 * @throws \ImagickException
84 private function magic(int $cid, string $url)
86 $visitor = $this->session->getMyUrl();
87 if (!empty($visitor)) {
88 $this->logger->info('Got my url', ['visitor' => $visitor]);
91 $contact = $this->database->selectFirst('contact', ['url'], ['id' => $cid]);
93 $this->logger->info('Contact not found', ['id' => $cid]);
94 throw new HTTPException\NotFoundException($this->t('Contact not found.'));
96 $contact_url = $contact['url'];
97 $this->checkUrl($contact_url, $url);
98 $target_url = $url ?: $contact_url;
101 $basepath = Contact::getBasepath($contact_url);
103 // We don't use magic auth when there is no visitor, we are on the same system, or we visit our own stuff
104 if (empty($visitor) || Strings::compareLink($basepath, $this->baseUrl) || Strings::compareLink($contact_url, $visitor)) {
105 $this->logger->info('Redirecting without magic', ['target' => $target_url, 'visitor' => $visitor, 'contact' => $contact_url]);
106 $this->app->redirect($target_url);
109 // Test for magic auth on the target system
110 $response = $this->httpClient->head($basepath . '/magic', [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::HTML]);
111 if ($response->isSuccess()) {
112 $separator = strpos($target_url, '?') ? '&' : '?';
113 $target_url .= $separator . 'zrl=' . urlencode($visitor) . '&addr=' . urlencode($contact_url);
115 $this->logger->info('Redirecting with magic', ['target' => $target_url, 'visitor' => $visitor, 'contact' => $contact_url]);
116 $this->app->redirect($target_url);
118 $this->logger->info('No magic for contact', ['contact' => $contact_url]);
126 * @throws HTTPException\BadRequestException
127 * @throws HTTPException\ForbiddenException
128 * @throws HTTPException\InternalServerErrorException
129 * @throws HTTPException\NotFoundException
131 private function legacy(int $cid, string $url): void
134 throw new HTTPException\BadRequestException($this->t('Bad Request.'));
137 $fields = ['id', 'uid', 'nurl', 'url', 'addr', 'name'];
138 $contact = $this->database->selectFirst('contact', $fields, ['id' => $cid, 'uid' => [0, $this->session->getLocalUserId()]]);
140 throw new HTTPException\NotFoundException($this->t('Contact not found.'));
143 $contact_url = $contact['url'];
145 if (!empty($this->app->getContactId()) && $this->app->getContactId() == $cid) {
146 // Local user is already authenticated.
147 $this->checkUrl($contact_url, $url);
148 $this->app->redirect($url ?: $contact_url);
151 if ($contact['uid'] == 0 && $this->session->getLocalUserId()) {
152 // Let's have a look if there is an established connection
153 // between the public contact we have found and the local user.
154 $contact = $this->database->selectFirst('contact', $fields, ['nurl' => $contact['nurl'], 'uid' => $this->session->getLocalUserId()]);
156 $cid = $contact['id'];
159 if (!empty($this->app->getContactId()) && $this->app->getContactId() == $cid) {
160 // Local user is already authenticated.
161 $this->checkUrl($contact_url, $url);
162 $target_url = $url ?: $contact_url;
163 $this->logger->info($contact['name'] . " is already authenticated. Redirecting to " . $target_url);
164 $this->app->redirect($target_url);
168 if ($this->session->getRemoteUserId()) {
169 $host = substr($this->baseUrl->getPath() . ($this->baseUrl->getPath() ? '/' . $this->baseUrl->getPath() : ''), strpos($this->baseUrl->getPath(), '://') + 3);
170 $remotehost = substr($contact['addr'], strpos($contact['addr'], '@') + 1);
172 // On a local instance we have to check if the local user has already authenticated
173 // with the local contact. Otherwise, the local user would ask the local contact
174 // for authentication everytime he/she is visiting a profile page of the local
176 if (($host == $remotehost) && ($this->session->getRemoteContactID($this->session->get('visitor_visiting')) == $this->session->get('visitor_id'))) {
177 // Remote user is already authenticated.
178 $this->checkUrl($contact_url, $url);
179 $target_url = $url ?: $contact_url;
180 $this->logger->info($contact['name'] . " is already authenticated. Redirecting to " . $target_url);
181 $this->app->redirect($target_url);
186 throw new HTTPException\BadRequestException($this->t('Bad Request.'));
189 // If we don't have a connected contact, redirect with
190 // the 'zrl' parameter.
191 $my_profile = $this->session->getMyUrl();
193 if (!empty($my_profile) && !Strings::compareLink($my_profile, $url)) {
194 $separator = strpos($url, '?') ? '&' : '?';
196 $url .= $separator . 'zrl=' . urlencode($my_profile);
199 $this->logger->info('redirecting to ' . $url);
200 $this->app->redirect($url);
204 private function checkUrl(string $contact_url, string $url)
206 if (empty($contact_url) || empty($url)) {
210 $url_host = parse_url($url, PHP_URL_HOST);
211 if (empty($url_host)) {
212 $url_host = parse_url($this->baseUrl, PHP_URL_HOST);
215 $contact_url_host = parse_url($contact_url, PHP_URL_HOST);
217 if ($url_host == $contact_url_host) {
221 $this->logger->error('URL check host mismatch', ['contact' => $contact_url, 'url' => $url]);
222 throw new HTTPException\ForbiddenException($this->t('Access denied.'));