]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/apiauth.php
Merge branch 'testing' into 0.9.x
[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 /* External API usage documentation. Please update when you change how this method works. */
38
39 /*! @page authentication Authentication
40
41     StatusNet supports HTTP Basic Authentication and OAuth for API calls.
42
43     @warning Currently, users who have created accounts without setting a
44     password via OpenID, Facebook Connect, etc., cannot use the API until
45     they set a password with their account settings panel.
46
47     @section HTTP Basic Auth
48
49
50
51     @section OAuth
52
53 */
54
55 if (!defined('STATUSNET')) {
56     exit(1);
57 }
58
59 require_once INSTALLDIR . '/lib/apioauth.php';
60
61 /**
62  * Actions extending this class will require auth
63  *
64  * @category API
65  * @package  StatusNet
66  * @author   Zach Copley <zach@status.net>
67  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
68  * @link     http://status.net/
69  */
70
71 class ApiAuthAction extends ApiAction
72 {
73     var $auth_user_nickname = null;
74     var $auth_user_password = null;
75
76     /**
77      * Take arguments for running, looks for an OAuth request,
78      * and outputs basic auth header if needed
79      *
80      * @param array $args $_REQUEST args
81      *
82      * @return boolean success flag
83      *
84      */
85
86     function prepare($args)
87     {
88         parent::prepare($args);
89
90         // NOTE: $this->auth_user has to get set in prepare(), not handle(),
91         // because subclasses do stuff with it in their prepares.
92
93         $oauthReq = $this->getOAuthRequest();
94
95         if (!$oauthReq) {
96             if ($this->requiresAuth()) {
97                 $this->checkBasicAuthUser(true);
98             } else {
99                 // Check to see if a basic auth user is there even
100                 // if one's not required
101                 $this->checkBasicAuthUser(false);
102             }
103         } else {
104             $this->checkOAuthRequest($oauthReq);
105         }
106
107         // Reject API calls with the wrong access level
108
109         if ($this->isReadOnly($args) == false) {
110             if ($this->access != self::READ_WRITE) {
111                 // TRANS: Client error 401.
112                 $msg = _('API resource requires read-write access, ' .
113                          'but you only have read access.');
114                 $this->clientError($msg, 401, $this->format);
115                 exit;
116             }
117         }
118
119         return true;
120     }
121
122     /**
123      * Determine whether the request is an OAuth request.
124      * This is to avoid doign any unnecessary DB lookups.
125      *
126      * @return mixed the OAuthRequest or false
127      */
128
129     function getOAuthRequest()
130     {
131         ApiOauthAction::cleanRequest();
132
133         $req  = OAuthRequest::from_request();
134
135         $consumer    = $req->get_parameter('oauth_consumer_key');
136         $accessToken = $req->get_parameter('oauth_token');
137
138         // XXX: Is it good enough to assume it's not meant to be an
139         // OAuth request if there is no consumer or token? --Z
140
141         if (empty($consumer) || empty($accessToken)) {
142             return false;
143         }
144
145         return $req;
146     }
147
148     /**
149      * Verifies the OAuth request signature, sets the auth user
150      * and access type (read-only or read-write)
151      *
152      * @param OAuthRequest $request the OAuth Request
153      *
154      * @return nothing
155      */
156
157     function checkOAuthRequest($request)
158     {
159         $datastore   = new ApiStatusNetOAuthDataStore();
160         $server      = new OAuthServer($datastore);
161         $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
162
163         $server->add_signature_method($hmac_method);
164
165         try {
166
167             $server->verify_request($request);
168
169             $consumer     = $request->get_parameter('oauth_consumer_key');
170             $access_token = $request->get_parameter('oauth_token');
171
172             $app = Oauth_application::getByConsumerKey($consumer);
173
174             if (empty($app)) {
175                 common_log(LOG_WARNING,
176                            'Couldn\'t find the OAuth app for consumer key: ' .
177                            $consumer);
178                 throw new OAuthException('No application for that consumer key.');
179             }
180
181             // set the source attr
182
183             $this->source = $app->name;
184
185             $appUser = Oauth_application_user::staticGet('token', $access_token);
186
187             if (!empty($appUser)) {
188
189                 // If access_type == 0 we have either a request token
190                 // or a bad / revoked access token
191
192                 if ($appUser->access_type != 0) {
193
194                     // Set the access level for the api call
195
196                     $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
197                       ? self::READ_WRITE : self::READ_ONLY;
198
199                     // Set the auth user
200
201                     if (Event::handle('StartSetApiUser', array(&$user))) {
202                         $this->auth_user = User::staticGet('id', $appUser->profile_id);
203                         Event::handle('EndSetApiUser', array($user));
204                     }
205
206                     $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
207                       "application '%s' (id: %d) with %s access.";
208
209                     common_log(LOG_INFO, sprintf($msg,
210                                                  $this->auth_user->nickname,
211                                                  $this->auth_user->id,
212                                                  $app->name,
213                                                  $app->id,
214                                                  ($this->access = self::READ_WRITE) ?
215                                                  'read-write' : 'read-only'
216                                                  ));
217                 } else {
218                     throw new OAuthException('Bad access token.');
219                 }
220             } else {
221
222                 // Also should not happen
223
224                 throw new OAuthException('No user for that token.');
225             }
226
227         } catch (OAuthException $e) {
228             common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
229             $this->showAuthError();
230             exit;
231         }
232     }
233
234     /**
235      * Does this API resource require authentication?
236      *
237      * @return boolean true
238      */
239
240     function requiresAuth()
241     {
242         return true;
243     }
244
245     /**
246      * Check for a user specified via HTTP basic auth. If there isn't
247      * one, try to get one by outputting the basic auth header.
248      *
249      * @return boolean true or false
250      */
251
252     function checkBasicAuthUser($required = true)
253     {
254         $this->basicAuthProcessHeader();
255
256         $realm = common_config('api', 'realm');
257
258         if (empty($realm)) {
259             $realm = common_config('site', 'name') . ' API';
260         }
261
262         if (empty($this->auth_user_nickname) && $required) {
263             header('WWW-Authenticate: Basic realm="' . $realm . '"');
264
265             // show error if the user clicks 'cancel'
266
267             $this->showAuthError();
268             exit;
269
270         } else {
271
272             $user = common_check_user($this->auth_user_nickname,
273                                       $this->auth_user_password);
274
275             if (Event::handle('StartSetApiUser', array(&$user))) {
276
277                 if (!empty($user)) {
278                     $this->auth_user = $user;
279                 }
280
281                 Event::handle('EndSetApiUser', array($user));
282             }
283
284             // By default, basic auth users have rw access
285
286             $this->access = self::READ_WRITE;
287
288             if (empty($this->auth_user) && ($required || isset($_SERVER['PHP_AUTH_USER']))) {
289
290                 // basic authentication failed
291
292                 list($proxy, $ip) = common_client_ip();
293
294                 $msg = sprintf( 'Failed API auth attempt, nickname = %1$s, ' .
295                          'proxy = %2$s, ip = %3$s',
296                                $this->auth_user_nickname,
297                                $proxy,
298                                $ip);
299                 common_log(LOG_WARNING, $msg);
300                 $this->showAuthError();
301                 exit;
302             }
303         }
304     }
305
306     /**
307      * Read the HTTP headers and set the auth user.  Decodes HTTP_AUTHORIZATION
308      * param to support basic auth when PHP is running in CGI mode.
309      *
310      * @return void
311      */
312
313     function basicAuthProcessHeader()
314     {
315         $authHeaders = array('AUTHORIZATION',
316                              'HTTP_AUTHORIZATION',
317                              'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
318         $authorization_header = null;
319         foreach ($authHeaders as $header) {
320             if (isset($_SERVER[$header])) {
321                 $authorization_header = $_SERVER[$header];
322                 break;
323             }
324         }
325
326         if (isset($_SERVER['PHP_AUTH_USER'])) {
327             $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
328             $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
329         } elseif (isset($authorization_header)
330             && strstr(substr($authorization_header, 0, 5), 'Basic')) {
331
332             // Decode the HTTP_AUTHORIZATION header on php-cgi server self
333             // on fcgid server the header name is AUTHORIZATION
334
335             $auth_hash = base64_decode(substr($authorization_header, 6));
336             list($this->auth_user_nickname,
337                  $this->auth_user_password) = explode(':', $auth_hash);
338
339             // Set all to null on a empty basic auth request
340
341             if (empty($this->auth_user_nickname)) {
342                 $this->auth_user_nickname = null;
343                 $this->auth_password = null;
344             }
345         }
346     }
347
348     /**
349      * Output an authentication error message.  Use XML or JSON if one
350      * of those formats is specified, otherwise output plain text
351      *
352      * @return void
353      */
354
355     function showAuthError()
356     {
357         header('HTTP/1.1 401 Unauthorized');
358         $msg = 'Could not authenticate you.';
359
360         if ($this->format == 'xml') {
361             header('Content-Type: application/xml; charset=utf-8');
362             $this->startXML();
363             $this->elementStart('hash');
364             $this->element('error', null, $msg);
365             $this->element('request', null, $_SERVER['REQUEST_URI']);
366             $this->elementEnd('hash');
367             $this->endXML();
368         } elseif ($this->format == 'json') {
369             header('Content-Type: application/json; charset=utf-8');
370             $error_array = array('error' => $msg,
371                                  'request' => $_SERVER['REQUEST_URI']);
372             print(json_encode($error_array));
373         } else {
374             header('Content-type: text/plain');
375             print "$msg\n";
376         }
377     }
378
379 }