]> git.mxchange.org Git - friendica.git/blob - src/Security/OAuth.php
Merge pull request #11060 from urbalazs/typo
[friendica.git] / src / Security / OAuth.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 Friendica\Core\Logger;
25 use Friendica\Database\Database;
26 use Friendica\Database\DBA;
27 use Friendica\Module\BaseApi;
28 use Friendica\Util\DateTimeFormat;
29
30 /**
31  * OAuth Server
32  */
33 class OAuth
34 {
35         /**
36          * @var bool|int
37          */
38         protected static $current_user_id = 0;
39         /**
40          * @var array
41          */
42         protected static $current_token = [];
43
44         /**
45          * Get current user id, returns 0 if not logged in
46          *
47          * @return int User ID
48          */
49         public static function getCurrentUserID()
50         {
51                 if (empty(self::$current_user_id)) {
52                         $token = self::getCurrentApplicationToken();
53                         if (!empty($token['uid'])) {
54                                 self::$current_user_id = $token['uid'];
55                         } else {
56                                 self::$current_user_id = 0;
57                         }
58                 }
59
60                 return (int)self::$current_user_id;
61         }
62
63         /**
64          * Get current application token
65          *
66          * @return array token
67          */
68         public static function getCurrentApplicationToken()
69         {
70                 if (empty(self::$current_token)) {
71                         self::$current_token = self::getTokenByBearer();
72                 }
73
74                 return self::$current_token;
75         }
76
77         /**
78          * Get the user token via the Bearer token
79          *
80          * @return array User Token
81          */
82         private static function getTokenByBearer()
83         {
84                 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
85
86                 if (empty($authorization)) {
87                         // workaround for HTTP-auth in CGI mode
88                         $authorization = $_SERVER['REDIRECT_REMOTE_USER'] ?? '';
89                 }
90
91                 if (substr($authorization, 0, 7) != 'Bearer ') {
92                         return [];
93                 }
94
95                 $condition = ['access_token' => trim(substr($authorization, 7))];
96
97                 $token = DBA::selectFirst('application-view', ['uid', 'id', 'name', 'website', 'created_at', 'read', 'write', 'follow', 'push'], $condition);
98                 if (!DBA::isResult($token)) {
99                         Logger::warning('Token not found', $condition);
100                         return [];
101                 }
102                 Logger::debug('Token found', $token);
103                 return $token;
104         }
105
106         /**
107          * Get the application record via the provided request header fields
108          *
109          * @param string $client_id
110          * @param string $client_secret
111          * @param string $redirect_uri
112          * @return array application record
113          */
114         public static function getApplication(string $client_id, string $client_secret, string $redirect_uri)
115         {
116                 $condition = ['client_id' => $client_id];
117                 if (!empty($client_secret)) {
118                         $condition['client_secret'] = $client_secret;
119                 }
120                 if (!empty($redirect_uri)) {
121                         $condition['redirect_uri'] = $redirect_uri;
122                 }
123
124                 $application = DBA::selectFirst('application', [], $condition);
125                 if (!DBA::isResult($application)) {
126                         Logger::warning('Application not found', $condition);
127                         return [];
128                 }
129                 return $application;
130         }
131
132         /**
133          * Check if an token for the application and user exists
134          *
135          * @param array $application
136          * @param integer $uid
137          * @return boolean
138          */
139         public static function existsTokenForUser(array $application, int $uid)
140         {
141                 return DBA::exists('application-token', ['application-id' => $application['id'], 'uid' => $uid]);
142         }
143
144         /**
145          * Fetch the token for the given application and user
146          *
147          * @param array $application
148          * @param integer $uid
149          * @return array application record
150          */
151         public static function getTokenForUser(array $application, int $uid)
152         {
153                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
154         }
155
156         /**
157          * Create and fetch an token for the application and user
158          *
159          * @param array   $application
160          * @param integer $uid
161          * @param string  $scope
162          * @return array application record
163          */
164         public static function createTokenForUser(array $application, int $uid, string $scope)
165         {
166                 $code         = bin2hex(random_bytes(32));
167                 $access_token = bin2hex(random_bytes(32));
168
169                 $fields = [
170                         'application-id' => $application['id'],
171                         'uid'            => $uid,
172                         'code'           => $code,
173                         'access_token'   => $access_token,
174                         'scopes'         => $scope,
175                         'read'           => (stripos($scope, BaseApi::SCOPE_READ) !== false),
176                         'write'          => (stripos($scope, BaseApi::SCOPE_WRITE) !== false),
177                         'follow'         => (stripos($scope, BaseApi::SCOPE_FOLLOW) !== false),
178                         'push'           => (stripos($scope, BaseApi::SCOPE_PUSH) !== false),
179                         'created_at'     => DateTimeFormat::utcNow()];
180
181                 foreach ([BaseApi::SCOPE_READ, BaseApi::SCOPE_WRITE, BaseApi::SCOPE_WRITE, BaseApi::SCOPE_PUSH] as $scope) {
182                         if ($fields[$scope] && !$application[$scope]) {
183                                 Logger::warning('Requested token scope is not allowed for the application', ['token' => $fields, 'application' => $application]);
184                         }
185                 }
186
187                 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
188                         return [];
189                 }
190
191                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
192         }
193 }