]> git.mxchange.org Git - friendica.git/blob - src/Security/BasicAuth.php
Replace REGEXP with LOCATE for allow_cid and deny_cid
[friendica.git] / src / Security / BasicAuth.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\Security;
23
24 use Exception;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Session;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Model\User;
31 use Friendica\Network\HTTPException\UnauthorizedException;
32 use Friendica\Util\DateTimeFormat;
33
34 /**
35  * Authentification via the basic auth method
36  */
37 class BasicAuth
38 {
39         /**
40          * @var bool|int
41          */
42         protected static $current_user_id = 0;
43         /**
44          * @var array
45          */
46         protected static $current_token = [];
47
48         /**
49          * Get current user id, returns 0 if $login is set to false and not logged in.
50          * When $login is true, the execution will stop when not logged in.
51          *
52          * @param bool $login Perform a login request if "true"
53          *
54          * @return int User ID
55          */
56         public static function getCurrentUserID(bool $login)
57         {
58                 if (empty(self::$current_user_id)) {
59                         self::$current_user_id = self::getUserIdByAuth($login);
60                 }
61
62                 return (int)self::$current_user_id;
63         }
64
65         /**
66          * Fetch a dummy application token
67          *
68          * @return array token
69          */
70         public static function getCurrentApplicationToken()
71         {
72                 if (empty(self::getCurrentUserID(true))) {
73                         return [];
74                 }
75
76                 if (!empty(self::$current_token)) {
77                         return self::$current_token;
78                 }
79
80                 $source = $_REQUEST['source'] ?? '';
81
82                 // Support for known clients that doesn't send a source name
83                 if (empty($source) && !empty($_SERVER['HTTP_USER_AGENT'])) {
84                         if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
85                                 $source = 'Twidere';
86                         }
87
88                         Logger::info('Unrecognized user-agent', ['http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
89                 } else {
90                         Logger::info('Empty user-agent');
91                 }
92
93                 if (empty($source)) {
94                         $source = 'api';
95                 }
96
97                 self::$current_token = [
98                         'uid'        => self::$current_user_id,
99                         'id'         => 0,
100                         'name'       => $source,
101                         'website'    => '',
102                         'created_at' => DBA::NULL_DATETIME,
103                         'read'       => true,
104                         'write'      => true,
105                         'follow'     => true,
106                         'push'       => false];
107
108                 return self::$current_token;
109         }
110
111         /**
112          * Fetch the user id via the auth header information
113          *
114          * @param boolean $do_login Perform a login request if not logged in
115          *
116          * @return integer User ID
117          */
118         private static function getUserIdByAuth(bool $do_login = true):int
119         {
120                 $a = DI::app();
121                 Session::set('allow_api', false);
122                 self::$current_user_id = 0;
123
124                 // workaround for HTTP-auth in CGI mode
125                 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
126                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
127                         if (!empty($userpass) && strpos($userpass, ':')) {
128                                 list($name, $password) = explode(':', $userpass);
129                                 $_SERVER['PHP_AUTH_USER'] = $name;
130                                 $_SERVER['PHP_AUTH_PW'] = $password;
131                         }
132                 }
133
134                 $user     = $_SERVER['PHP_AUTH_USER'] ?? '';
135                 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
136
137                 // allow "user@server" login (but ignore 'server' part)
138                 $at = strstr($user, "@", true);
139                 if ($at) {
140                         $user = $at;
141                 }
142
143                 // next code from mod/auth.php. needs better solution
144                 $record = null;
145
146                 $addon_auth = [
147                         'username' => trim($user),
148                         'password' => trim($password),
149                         'authenticated' => 0,
150                         'user_record' => null,
151                 ];
152
153                 /*
154                 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
155                 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
156                 * and later addons should not interfere with an earlier one that succeeded.
157                 */
158                 Hook::callAll('authenticate', $addon_auth);
159
160                 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
161                         $record = $addon_auth['user_record'];
162                 } else {
163                         try {
164                                 $user_id = User::getIdFromPasswordAuthentication(trim($user), trim($password), true);
165                                 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
166                         } catch (Exception $ex) {
167                                 $record = [];
168                         }
169                 }
170
171                 if (empty($record)) {
172                         if (!$do_login) {
173                                 return 0;
174                         }
175                         Logger::debug('Access denied', ['parameters' => $_SERVER]);
176                         header('WWW-Authenticate: Basic realm="Friendica"');
177                         throw new UnauthorizedException("This API requires login");
178                 }
179
180                 // Don't refresh the login date more often than twice a day to spare database writes
181                 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
182
183                 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
184
185                 Session::set('allow_api', true);
186
187                 Hook::callAll('logged_in', $record);
188
189                 if (Session::get('allow_api')) {
190                         self::$current_user_id = local_user();
191                 } else {
192                         self::$current_user_id = 0;
193                 }
194                 return self::$current_user_id;
195         }
196 }