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