]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Login prototype
[friendica.git] / src / Module / BaseApi.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\Database;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Network\HTTPException;
31
32 require_once __DIR__ . '/../../include/api.php';
33
34 class BaseApi extends BaseModule
35 {
36         /**
37          * @var string json|xml|rss|atom
38          */
39         protected static $format = 'json';
40         /**
41          * @var bool|int
42          */
43         protected static $current_user_id;
44
45         public static function init(array $parameters = [])
46         {
47                 $arguments = DI::args();
48
49                 if (substr($arguments->getCommand(), -4) === '.xml') {
50                         self::$format = 'xml';
51                 }
52                 if (substr($arguments->getCommand(), -4) === '.rss') {
53                         self::$format = 'rss';
54                 }
55                 if (substr($arguments->getCommand(), -4) === '.atom') {
56                         self::$format = 'atom';
57                 }
58         }
59
60         public static function delete(array $parameters = [])
61         {
62                 if (!api_user()) {
63                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
64                 }
65
66                 $a = DI::app();
67
68                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
69                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
70                 }
71         }
72
73         public static function patch(array $parameters = [])
74         {
75                 if (!api_user()) {
76                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
77                 }
78
79                 $a = DI::app();
80
81                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
82                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
83                 }
84         }
85
86         public static function post(array $parameters = [])
87         {
88                 if (!api_user()) {
89                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
90                 }
91
92                 $a = DI::app();
93
94                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
95                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
96                 }
97         }
98
99         public static function put(array $parameters = [])
100         {
101                 if (!api_user()) {
102                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
103                 }
104
105                 $a = DI::app();
106
107                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
108                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
109                 }
110         }
111
112         public static function unsupported(string $method = 'all')
113         {
114                 $path = DI::args()->getQueryString();
115                 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => $_REQUEST ?? []]);
116                 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
117                 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');;
118                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
119                 System::jsonError(501, $errorobj->toArray());
120         }
121
122         /**
123          * Log in user via OAuth1 or Simple HTTP Auth.
124          *
125          * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
126          *
127          * @return bool Was a user authenticated?
128          * @throws HTTPException\ForbiddenException
129          * @throws HTTPException\UnauthorizedException
130          * @throws HTTPException\InternalServerErrorException
131          * @hook  'authenticate'
132          *               array $addon_auth
133          *               'username' => username from login form
134          *               'password' => password from login form
135          *               'authenticated' => return status,
136          *               'user_record' => return authenticated user record
137          */
138         protected static function login()
139         {
140                 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
141                 $authorization = $_SERVER['AUTHORIZATION'] ?? $authorization;
142
143                 if (self::checkBearer($authorization)) {
144                         self::$current_user_id = self::getUserByBearer($authorization);
145                         return (bool)self::$current_user_id;
146                 }
147
148                 api_login(DI::app());
149
150                 self::$current_user_id = api_user();
151
152                 return (bool)self::$current_user_id;
153         }
154
155         /**
156          * Get current user id, returns 0 if not logged in
157          *
158          * @return int User ID
159          */
160         protected static function getCurrentUserID()
161         {
162                 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
163                 $authorization = $_SERVER['AUTHORIZATION'] ?? $authorization;
164
165                 if (self::checkBearer($authorization)) {
166                         self::$current_user_id = self::getUserByBearer($authorization);
167                         return (int)self::$current_user_id;
168                 }
169
170                 if (is_null(self::$current_user_id)) {
171                         api_login(DI::app(), false);
172
173                         self::$current_user_id = api_user();
174                 }
175
176                 return (int)self::$current_user_id;
177         }
178
179         private static function checkBearer(string $authorization)
180         {
181                 return(strpos($authorization, 'Bearer ') !== false);
182         }
183
184         private static function getUserByBearer(string $authorization)
185         {
186                 $bearer = trim(substr($authorization, 6));
187                 $condition = ['access_token' => $bearer];
188                 $token = DBA::selectFirst('application-token', ['uid'], $condition);
189                 if (!DBA::isResult($token)) {
190                         Logger::warning('Token not found', $condition);
191                         return 0;
192                 }
193                 Logger::info('Token found', $token);
194                 return $token['uid'];
195         }
196
197         public static function getApplication()
198         {
199                 $redirect_uri = !isset($_REQUEST['redirect_uri']) ? '' : $_REQUEST['redirect_uri'];
200                 $client_id    = !isset($_REQUEST['client_id']) ? '' : $_REQUEST['client_id'];
201
202                 if (empty($redirect_uri) || empty($client_id)) {
203                         Logger::warning('Incomplete request');
204                         return [];
205                 }
206
207                 $condition = ['redirect_uri' => $redirect_uri, 'client_id' => $client_id];
208                 $application = DBA::selectFirst('application', [], $condition);
209                 if (!DBA::isResult($application)) {
210                         Logger::warning('Application not found', $condition);
211                         return [];
212                 }
213                 return $application;
214         }
215
216         public static function getTokenForUser(array $application, int $uid)
217         {
218                 $code         = bin2hex(openssl_random_pseudo_bytes(32));
219                 $access_token = bin2hex(openssl_random_pseudo_bytes(32));
220
221                 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token];
222                 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
223                         return [];
224                 }
225
226                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
227         }
228         /**
229          * Get user info array.
230          *
231          * @param int|string $contact_id Contact ID or URL
232          * @return array|bool
233          * @throws HTTPException\BadRequestException
234          * @throws HTTPException\InternalServerErrorException
235          * @throws HTTPException\UnauthorizedException
236          * @throws \ImagickException
237          */
238         protected static function getUser($contact_id = null)
239         {
240                 return api_get_user(DI::app(), $contact_id);
241         }
242
243         /**
244          * Formats the data according to the data type
245          *
246          * @param string $root_element
247          * @param array $data An array with a single element containing the returned result
248          * @return false|string
249          */
250         protected static function format(string $root_element, array $data)
251         {
252                 $return = api_format_data($root_element, self::$format, $data);
253
254                 switch (self::$format) {
255                         case "xml":
256                                 header("Content-Type: text/xml");
257                                 break;
258                         case "json":
259                                 header("Content-Type: application/json");
260                                 if (!empty($return)) {
261                                         $json = json_encode(end($return));
262                                         if (!empty($_GET['callback'])) {
263                                                 $json = $_GET['callback'] . "(" . $json . ")";
264                                         }
265                                         $return = $json;
266                                 }
267                                 break;
268                         case "rss":
269                                 header("Content-Type: application/rss+xml");
270                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
271                                 break;
272                         case "atom":
273                                 header("Content-Type: application/atom+xml");
274                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
275                                 break;
276                 }
277
278                 return $return;
279         }
280
281         /**
282          * Creates the XML from a JSON style array
283          *
284          * @param $data
285          * @param $root_element
286          * @return string
287          */
288         protected static function createXml($data, $root_element)
289         {
290                 return api_create_xml($data, $root_element);
291         }
292 }