]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/apiauth.php
Adjust API authentication to also check for OAuth protocol params in the
[quix0rs-gnu-social.git] / lib / apiauth.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Base class for API actions that require authentication
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  API
23  * @package   StatusNet
24  * @author    Adrian Lang <mail@adrianlang.de>
25  * @author    Brenda Wallace <shiny@cpan.org>
26  * @author    Craig Andrews <candrews@integralblue.com>
27  * @author    Dan Moore <dan@moore.cx>
28  * @author    Evan Prodromou <evan@status.net>
29  * @author    mEDI <medi@milaro.net>
30  * @author    Sarven Capadisli <csarven@status.net>
31  * @author    Zach Copley <zach@status.net>
32  * @copyright 2009-2010 StatusNet, Inc.
33  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
34  * @link      http://status.net/
35  */
36
37 if (!defined('STATUSNET')) {
38     exit(1);
39 }
40
41 require_once INSTALLDIR . '/lib/api.php';
42 require_once INSTALLDIR . '/lib/apioauth.php';
43
44 /**
45  * Actions extending this class will require auth
46  *
47  * @category API
48  * @package  StatusNet
49  * @author   Zach Copley <zach@status.net>
50  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
51  * @link     http://status.net/
52  */
53
54 class ApiAuthAction extends ApiAction
55 {
56     var $auth_user_nickname = null;
57     var $auth_user_password = null;
58
59     /**
60      * Take arguments for running, looks for an OAuth request,
61      * and outputs basic auth header if needed
62      *
63      * @param array $args $_REQUEST args
64      *
65      * @return boolean success flag
66      *
67      */
68
69     function prepare($args)
70     {
71         parent::prepare($args);
72
73         // NOTE: $this->auth_user has to get set in prepare(), not handle(),
74         // because subclasses do stuff with it in their prepares.
75
76         if ($this->requiresAuth()) {
77
78             $oauthReq = $this->getOAuthRequest();
79
80             if (!$oauthReq) {
81                 $this->checkBasicAuthUser(true);
82             } else {
83                 $this->checkOAuthRequest($oauthReq);
84             }
85         } else {
86
87             // Check to see if a basic auth user is there even
88             // if one's not required
89             $this->checkBasicAuthUser(false);
90         }
91
92         // Reject API calls with the wrong access level
93
94         if ($this->isReadOnly($args) == false) {
95             if ($this->access != self::READ_WRITE) {
96                 $msg = _('API resource requires read-write access, ' .
97                          'but you only have read access.');
98                 $this->clientError($msg, 401, $this->format);
99                 exit;
100             }
101         }
102
103         return true;
104     }
105
106     /**
107      * Determine whether the request is an OAuth request.
108      * This is to avoid doign any unnecessary DB lookups.
109      *
110      * @return mixed the OAuthRequest or false
111      *
112      */
113
114     function getOAuthRequest()
115     {
116         ApiOauthAction::cleanRequest();
117
118         $req  = OAuthRequest::from_request();
119
120         $consumer    = $req->get_parameter('oauth_consumer_key');
121         $accessToken = $req->get_parameter('oauth_token');
122
123         // XXX: Is it good enough to assume it's not meant to be an
124         // OAuth request if there is no consumer or token? --Z
125
126         if (empty($consumer) || empty($accessToken)) {
127             return false;
128         }
129
130         return $req;
131     }
132
133     /**
134      * Verifies the OAuth request signature, sets the auth user
135      * and access type (read-only or read-write)
136      *
137      * @param OAuthRequest $request the OAuth Request
138      *
139      * @return nothing
140      *
141      */
142
143     function checkOAuthRequest($request)
144     {
145         $datastore   = new ApiStatusNetOAuthDataStore();
146         $server      = new OAuthServer($datastore);
147         $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
148
149         $server->add_signature_method($hmac_method);
150
151         try {
152
153             $server->verify_request($request);
154
155             $consumer     = $request->get_parameter('oauth_consumer_key');
156             $access_token = $request->get_parameter('oauth_token');
157
158             $app = Oauth_application::getByConsumerKey($consumer);
159
160             if (empty($app)) {
161                 common_log(LOG_WARNING,
162                            'Couldn\'t find the OAuth app for consumer key: ' .
163                            $consumer);
164                 throw new OAuthException('No application for that consumer key.');
165             }
166
167             // set the source attr
168
169             $this->oauth_source = $app->name;
170
171             $appUser = Oauth_application_user::staticGet('token', $access_token);
172
173             if (!empty($appUser)) {
174
175                 // If access_type == 0 we have either a request token
176                 // or a bad / revoked access token
177
178                 if ($appUser->access_type != 0) {
179
180                     // Set the access level for the api call
181
182                     $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
183                       ? self::READ_WRITE : self::READ_ONLY;
184
185                     // Set the auth user
186
187                     if (Event::handle('StartSetApiUser', array(&$user))) {
188                         $this->auth_user = User::staticGet('id', $appUser->profile_id);
189                         Event::handle('EndSetApiUser', array($user));
190                     }
191
192                     $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
193                       "application '%s' (id: %d) with %s access.";
194
195                     common_log(LOG_INFO, sprintf($msg,
196                                                  $this->auth_user->nickname,
197                                                  $this->auth_user->id,
198                                                  $app->name,
199                                                  $app->id,
200                                                  ($this->access = self::READ_WRITE) ?
201                                                  'read-write' : 'read-only'
202                                                  ));
203                 } else {
204                     throw new OAuthException('Bad access token.');
205                 }
206             } else {
207
208                 // Also should not happen
209
210                 throw new OAuthException('No user for that token.');
211             }
212
213         } catch (OAuthException $e) {
214             common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
215             $this->showAuthError();
216             exit;
217         }
218     }
219
220     /**
221      * Does this API resource require authentication?
222      *
223      * @return boolean true
224      */
225
226     function requiresAuth()
227     {
228         return true;
229     }
230
231     /**
232      * Check for a user specified via HTTP basic auth. If there isn't
233      * one, try to get one by outputting the basic auth header.
234      *
235      * @return boolean true or false
236      */
237
238     function checkBasicAuthUser($required = true)
239     {
240         $this->basicAuthProcessHeader();
241
242         $realm = common_config('site', 'name') . ' API';
243
244         if (!isset($this->auth_user_nickname) && $required) {
245             header('WWW-Authenticate: Basic realm="' . $realm . '"');
246
247             // show error if the user clicks 'cancel'
248
249             $this->showAuthError();
250             exit;
251
252         } else {
253
254             $user = common_check_user($this->auth_user_nickname,
255                                       $this->auth_user_password);
256
257             if (Event::handle('StartSetApiUser', array(&$user))) {
258
259                 if (!empty($user)) {
260                     $this->auth_user = $user;
261                 }
262
263                 Event::handle('EndSetApiUser', array($user));
264             }
265
266             // By default, basic auth users have rw access
267
268             $this->access = self::READ_WRITE;
269
270             if (empty($this->auth_user) && $required) {
271
272                 // basic authentication failed
273
274                 list($proxy, $ip) = common_client_ip();
275
276                 $msg = sprintf(_('Failed API auth attempt, nickname = %1$s, ' .
277                          'proxy = %2$s, ip = %3$s'),
278                                $this->auth_user_nickname,
279                                $proxy,
280                                $ip);
281                 common_log(LOG_WARNING, $msg);
282                 $this->showAuthError();
283                 exit;
284             }
285         }
286     }
287
288     /**
289      * Read the HTTP headers and set the auth user.  Decodes HTTP_AUTHORIZATION
290      * param to support basic auth when PHP is running in CGI mode.
291      *
292      * @return void
293      */
294
295     function basicAuthProcessHeader()
296     {
297         if (isset($_SERVER['AUTHORIZATION'])
298             || isset($_SERVER['HTTP_AUTHORIZATION'])
299             ) {
300             $authorization_header = isset($_SERVER['HTTP_AUTHORIZATION'])
301               ? $_SERVER['HTTP_AUTHORIZATION'] : $_SERVER['AUTHORIZATION'];
302         }
303
304         if (isset($_SERVER['PHP_AUTH_USER'])) {
305             $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
306             $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
307         } elseif (isset($authorization_header)
308             && strstr(substr($authorization_header, 0, 5), 'Basic')) {
309
310             // Decode the HTTP_AUTHORIZATION header on php-cgi server self
311             // on fcgid server the header name is AUTHORIZATION
312
313             $auth_hash = base64_decode(substr($authorization_header, 6));
314             list($this->auth_user_nickname,
315                  $this->auth_user_password) = explode(':', $auth_hash);
316
317             // Set all to null on a empty basic auth request
318
319             if (empty($this->auth_user_nickname)) {
320                 $this->auth_user_nickname = null;
321                 $this->auth_password = null;
322             }
323         }
324     }
325
326     /**
327      * Output an authentication error message.  Use XML or JSON if one
328      * of those formats is specified, otherwise output plain text
329      *
330      * @return void
331      */
332
333     function showAuthError()
334     {
335         header('HTTP/1.1 401 Unauthorized');
336         $msg = 'Could not authenticate you.';
337
338         if ($this->format == 'xml') {
339             header('Content-Type: application/xml; charset=utf-8');
340             $this->startXML();
341             $this->elementStart('hash');
342             $this->element('error', null, $msg);
343             $this->element('request', null, $_SERVER['REQUEST_URI']);
344             $this->elementEnd('hash');
345             $this->endXML();
346         } elseif ($this->format == 'json') {
347             header('Content-Type: application/json; charset=utf-8');
348             $error_array = array('error' => $msg,
349                                  'request' => $_SERVER['REQUEST_URI']);
350             print(json_encode($error_array));
351         } else {
352             header('Content-type: text/plain');
353             print "$msg\n";
354         }
355     }
356
357 }