]> git.mxchange.org Git - friendica.git/blob - src/Security/BasicAuth.php
Move basic auth functionality to the new class
[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                 self::$current_token = [
81                         'uid'        => self::$current_user_id,
82                         'id'         => 0,
83                         'name'       => api_source(),
84                         'website'    => '',
85                         'created_at' => DBA::NULL_DATETIME,
86                         'read'       => true,
87                         'write'      => true,
88                         'follow'     => true,
89                         'push'       => false];
90
91                 return self::$current_token;
92         }
93
94         /**
95          * Fetch the user id via the auth header information
96          *
97          * @param boolean $do_login Perform a login request if not logged in
98          *
99          * @return integer User ID
100          */
101         private static function getUserIdByAuth(bool $do_login = true):int
102         {
103                 $a = DI::app();
104                 Session::set('allow_api', false);
105                 self::$current_user_id = 0;
106
107                 // workaround for HTTP-auth in CGI mode
108                 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
109                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
110                         if (strlen($userpass)) {
111                                 list($name, $password) = explode(':', $userpass);
112                                 $_SERVER['PHP_AUTH_USER'] = $name;
113                                 $_SERVER['PHP_AUTH_PW'] = $password;
114                         }
115                 }
116
117                 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
118                 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
119         
120                 // allow "user@server" login (but ignore 'server' part)
121                 $at = strstr($user, "@", true);
122                 if ($at) {
123                         $user = $at;
124                 }
125         
126                 // next code from mod/auth.php. needs better solution
127                 $record = null;
128         
129                 $addon_auth = [
130                         'username' => trim($user),
131                         'password' => trim($password),
132                         'authenticated' => 0,
133                         'user_record' => null,
134                 ];
135         
136                 /*
137                 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
138                 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
139                 * and later addons should not interfere with an earlier one that succeeded.
140                 */
141                 Hook::callAll('authenticate', $addon_auth);
142         
143                 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
144                         $record = $addon_auth['user_record'];
145                 } else {
146                         try {
147                                 $user_id = User::getIdFromPasswordAuthentication(trim($user), trim($password), true);
148                                 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
149                         } catch (Exception $ex) {
150                                 $record = [];
151                         }                       
152                 }
153         
154                 if (empty($record)) {
155                         if (!$do_login) {
156                                 return 0;
157                         }
158                         Logger::debug('failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
159                         header('WWW-Authenticate: Basic realm="Friendica"');
160                         throw new UnauthorizedException("This API requires login");
161                 }
162         
163                 // Don't refresh the login date more often than twice a day to spare database writes
164                 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
165         
166                 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
167         
168                 Session::set('allow_api', true);
169         
170                 Hook::callAll('logged_in', $a->user);
171         
172                 if (Session::get('allow_api')) {
173                         self::$current_user_id = local_user();
174                 } else {
175                         self::$current_user_id = 0;
176                 }
177                 return self::$current_user_id;
178         }       
179 }