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