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