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