3 * StatusNet, the distributed open-source microblogging tool
5 * Base class for API actions that require authentication
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.
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.
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/>.
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/
37 /* External API usage documentation. Please update when you change how this method works. */
39 /*! @page authentication Authentication
41 StatusNet supports HTTP Basic Authentication and OAuth for API calls.
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.
47 @section HTTP Basic Auth
55 if (!defined('STATUSNET')) {
59 require_once INSTALLDIR . '/lib/apioauth.php';
62 * Actions extending this class will require auth
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/
71 class ApiAuthAction extends ApiAction
73 var $auth_user_nickname = null;
74 var $auth_user_password = null;
77 * Take arguments for running, looks for an OAuth request,
78 * and outputs basic auth header if needed
80 * @param array $args $_REQUEST args
82 * @return boolean success flag
86 function prepare($args)
88 parent::prepare($args);
90 // NOTE: $this->auth_user has to get set in prepare(), not handle(),
91 // because subclasses do stuff with it in their prepares.
93 $oauthReq = $this->getOAuthRequest();
96 if ($this->requiresAuth()) {
97 $this->checkBasicAuthUser(true);
99 // Check to see if a basic auth user is there even
100 // if one's not required
101 $this->checkBasicAuthUser(false);
104 $this->checkOAuthRequest($oauthReq);
107 // Reject API calls with the wrong access level
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);
123 * Determine whether the request is an OAuth request.
124 * This is to avoid doign any unnecessary DB lookups.
126 * @return mixed the OAuthRequest or false
129 function getOAuthRequest()
131 ApiOauthAction::cleanRequest();
133 $req = OAuthRequest::from_request();
135 $consumer = $req->get_parameter('oauth_consumer_key');
136 $accessToken = $req->get_parameter('oauth_token');
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
141 if (empty($consumer) || empty($accessToken)) {
149 * Verifies the OAuth request signature, sets the auth user
150 * and access type (read-only or read-write)
152 * @param OAuthRequest $request the OAuth Request
157 function checkOAuthRequest($request)
159 $datastore = new ApiStatusNetOAuthDataStore();
160 $server = new OAuthServer($datastore);
161 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
163 $server->add_signature_method($hmac_method);
167 $server->verify_request($request);
169 $consumer = $request->get_parameter('oauth_consumer_key');
170 $access_token = $request->get_parameter('oauth_token');
172 $app = Oauth_application::getByConsumerKey($consumer);
175 common_log(LOG_WARNING,
176 'Couldn\'t find the OAuth app for consumer key: ' .
178 throw new OAuthException('No application for that consumer key.');
181 // set the source attr
183 $this->source = $app->name;
185 $appUser = Oauth_application_user::staticGet('token', $access_token);
187 if (!empty($appUser)) {
189 // If access_type == 0 we have either a request token
190 // or a bad / revoked access token
192 if ($appUser->access_type != 0) {
194 // Set the access level for the api call
196 $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
197 ? self::READ_WRITE : self::READ_ONLY;
201 if (Event::handle('StartSetApiUser', array(&$user))) {
202 $this->auth_user = User::staticGet('id', $appUser->profile_id);
203 Event::handle('EndSetApiUser', array($user));
206 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
207 "application '%s' (id: %d) with %s access.";
209 common_log(LOG_INFO, sprintf($msg,
210 $this->auth_user->nickname,
211 $this->auth_user->id,
214 ($this->access = self::READ_WRITE) ?
215 'read-write' : 'read-only'
218 throw new OAuthException('Bad access token.');
222 // Also should not happen
224 throw new OAuthException('No user for that token.');
227 } catch (OAuthException $e) {
228 common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
229 $this->showAuthError();
235 * Does this API resource require authentication?
237 * @return boolean true
240 function requiresAuth()
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.
249 * @return boolean true or false
252 function checkBasicAuthUser($required = true)
254 $this->basicAuthProcessHeader();
256 $realm = common_config('api', 'realm');
259 $realm = common_config('site', 'name') . ' API';
262 if (empty($this->auth_user_nickname) && $required) {
263 header('WWW-Authenticate: Basic realm="' . $realm . '"');
265 // show error if the user clicks 'cancel'
267 $this->showAuthError();
272 $user = common_check_user($this->auth_user_nickname,
273 $this->auth_user_password);
275 if (Event::handle('StartSetApiUser', array(&$user))) {
278 $this->auth_user = $user;
281 Event::handle('EndSetApiUser', array($user));
284 // By default, basic auth users have rw access
286 $this->access = self::READ_WRITE;
288 if (empty($this->auth_user) && ($required || isset($_SERVER['PHP_AUTH_USER']))) {
290 // basic authentication failed
292 list($proxy, $ip) = common_client_ip();
294 $msg = sprintf( 'Failed API auth attempt, nickname = %1$s, ' .
295 'proxy = %2$s, ip = %3$s',
296 $this->auth_user_nickname,
299 common_log(LOG_WARNING, $msg);
300 $this->showAuthError();
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.
313 function basicAuthProcessHeader()
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];
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')) {
332 // Decode the HTTP_AUTHORIZATION header on php-cgi server self
333 // on fcgid server the header name is AUTHORIZATION
335 $auth_hash = base64_decode(substr($authorization_header, 6));
336 list($this->auth_user_nickname,
337 $this->auth_user_password) = explode(':', $auth_hash);
339 // Set all to null on a empty basic auth request
341 if (empty($this->auth_user_nickname)) {
342 $this->auth_user_nickname = null;
343 $this->auth_password = null;
349 * Output an authentication error message. Use XML or JSON if one
350 * of those formats is specified, otherwise output plain text
355 function showAuthError()
357 header('HTTP/1.1 401 Unauthorized');
358 $msg = 'Could not authenticate you.';
360 if ($this->format == 'xml') {
361 header('Content-Type: application/xml; charset=utf-8');
363 $this->elementStart('hash');
364 $this->element('error', null, $msg);
365 $this->element('request', null, $_SERVER['REQUEST_URI']);
366 $this->elementEnd('hash');
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));
374 header('Content-type: text/plain');