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 if (!defined('STATUSNET')) {
41 require_once INSTALLDIR . '/lib/apioauth.php';
44 * Actions extending this class will require auth
48 * @author Zach Copley <zach@status.net>
49 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
50 * @link http://status.net/
53 class ApiAuthAction extends ApiAction
55 var $auth_user_nickname = null;
56 var $auth_user_password = null;
57 var $oauth_source = null;
60 * Take arguments for running, looks for an OAuth request,
61 * and outputs basic auth header if needed
63 * @param array $args $_REQUEST args
65 * @return boolean success flag
69 function prepare($args)
71 parent::prepare($args);
73 // NOTE: $this->auth_user has to get set in prepare(), not handle(),
74 // because subclasses do stuff with it in their prepares.
76 $oauthReq = $this->getOAuthRequest();
79 if ($this->requiresAuth()) {
80 $this->checkBasicAuthUser(true);
82 // Check to see if a basic auth user is there even
83 // if one's not required
84 $this->checkBasicAuthUser(false);
87 $this->checkOAuthRequest($oauthReq);
90 // Reject API calls with the wrong access level
92 if ($this->isReadOnly($args) == false) {
93 if ($this->access != self::READ_WRITE) {
94 // TRANS: Client error 401.
95 $msg = _('API resource requires read-write access, ' .
96 'but you only have read access.');
97 $this->clientError($msg, 401, $this->format);
106 * Determine whether the request is an OAuth request.
107 * This is to avoid doign any unnecessary DB lookups.
109 * @return mixed the OAuthRequest or false
112 function getOAuthRequest()
114 ApiOauthAction::cleanRequest();
116 $req = OAuthRequest::from_request();
118 $consumer = $req->get_parameter('oauth_consumer_key');
119 $accessToken = $req->get_parameter('oauth_token');
121 // XXX: Is it good enough to assume it's not meant to be an
122 // OAuth request if there is no consumer or token? --Z
124 if (empty($consumer) || empty($accessToken)) {
132 * Verifies the OAuth request signature, sets the auth user
133 * and access type (read-only or read-write)
135 * @param OAuthRequest $request the OAuth Request
140 function checkOAuthRequest($request)
142 $datastore = new ApiStatusNetOAuthDataStore();
143 $server = new OAuthServer($datastore);
144 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
146 $server->add_signature_method($hmac_method);
150 $server->verify_request($request);
152 $consumer = $request->get_parameter('oauth_consumer_key');
153 $access_token = $request->get_parameter('oauth_token');
155 $app = Oauth_application::getByConsumerKey($consumer);
158 common_log(LOG_WARNING,
159 'Couldn\'t find the OAuth app for consumer key: ' .
161 throw new OAuthException('No application for that consumer key.');
164 // set the source attr
166 $this->oauth_source = $app->name;
168 $appUser = Oauth_application_user::staticGet('token', $access_token);
170 if (!empty($appUser)) {
172 // If access_type == 0 we have either a request token
173 // or a bad / revoked access token
175 if ($appUser->access_type != 0) {
177 // Set the access level for the api call
179 $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
180 ? self::READ_WRITE : self::READ_ONLY;
184 if (Event::handle('StartSetApiUser', array(&$user))) {
185 $this->auth_user = User::staticGet('id', $appUser->profile_id);
186 Event::handle('EndSetApiUser', array($user));
189 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
190 "application '%s' (id: %d) with %s access.";
192 common_log(LOG_INFO, sprintf($msg,
193 $this->auth_user->nickname,
194 $this->auth_user->id,
197 ($this->access = self::READ_WRITE) ?
198 'read-write' : 'read-only'
201 throw new OAuthException('Bad access token.');
205 // Also should not happen
207 throw new OAuthException('No user for that token.');
210 } catch (OAuthException $e) {
211 common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
212 $this->showAuthError();
218 * Does this API resource require authentication?
220 * @return boolean true
223 function requiresAuth()
229 * Check for a user specified via HTTP basic auth. If there isn't
230 * one, try to get one by outputting the basic auth header.
232 * @return boolean true or false
235 function checkBasicAuthUser($required = true)
237 $this->basicAuthProcessHeader();
239 $realm = common_config('api', 'realm');
242 $realm = common_config('site', 'name') . ' API';
245 if (empty($this->auth_user_nickname) && $required) {
246 header('WWW-Authenticate: Basic realm="' . $realm . '"');
248 // show error if the user clicks 'cancel'
250 $this->showAuthError();
255 $user = common_check_user($this->auth_user_nickname,
256 $this->auth_user_password);
258 if (Event::handle('StartSetApiUser', array(&$user))) {
261 $this->auth_user = $user;
264 Event::handle('EndSetApiUser', array($user));
267 // By default, basic auth users have rw access
269 $this->access = self::READ_WRITE;
271 if (empty($this->auth_user) && ($required || isset($_SERVER['PHP_AUTH_USER']))) {
273 // basic authentication failed
275 list($proxy, $ip) = common_client_ip();
277 $msg = sprintf( 'Failed API auth attempt, nickname = %1$s, ' .
278 'proxy = %2$s, ip = %3$s',
279 $this->auth_user_nickname,
282 common_log(LOG_WARNING, $msg);
283 $this->showAuthError();
290 * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
291 * param to support basic auth when PHP is running in CGI mode.
296 function basicAuthProcessHeader()
298 $authHeaders = array('AUTHORIZATION',
299 'HTTP_AUTHORIZATION',
300 'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
301 $authorization_header = null;
302 foreach ($authHeaders as $header) {
303 if (isset($_SERVER[$header])) {
304 $authorization_header = $_SERVER[$header];
309 if (isset($_SERVER['PHP_AUTH_USER'])) {
310 $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
311 $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
312 } elseif (isset($authorization_header)
313 && strstr(substr($authorization_header, 0, 5), 'Basic')) {
315 // Decode the HTTP_AUTHORIZATION header on php-cgi server self
316 // on fcgid server the header name is AUTHORIZATION
318 $auth_hash = base64_decode(substr($authorization_header, 6));
319 list($this->auth_user_nickname,
320 $this->auth_user_password) = explode(':', $auth_hash);
322 // Set all to null on a empty basic auth request
324 if (empty($this->auth_user_nickname)) {
325 $this->auth_user_nickname = null;
326 $this->auth_password = null;
332 * Output an authentication error message. Use XML or JSON if one
333 * of those formats is specified, otherwise output plain text
338 function showAuthError()
340 header('HTTP/1.1 401 Unauthorized');
341 $msg = 'Could not authenticate you.';
343 if ($this->format == 'xml') {
344 header('Content-Type: application/xml; charset=utf-8');
346 $this->elementStart('hash');
347 $this->element('error', null, $msg);
348 $this->element('request', null, $_SERVER['REQUEST_URI']);
349 $this->elementEnd('hash');
351 } elseif ($this->format == 'json') {
352 header('Content-Type: application/json; charset=utf-8');
353 $error_array = array('error' => $msg,
354 'request' => $_SERVER['REQUEST_URI']);
355 print(json_encode($error_array));
357 header('Content-type: text/plain');