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 * @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/
38 /* External API usage documentation. Please update when you change how this method works. */
40 /*! @page authentication Authentication
42 StatusNet supports HTTP Basic Authentication and OAuth for API calls.
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.
48 @section HTTP Basic Auth
56 if (!defined('STATUSNET')) {
60 require_once INSTALLDIR . '/lib/apioauth.php';
63 * Actions extending this class will require auth
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/
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
85 function prepare($args)
87 parent::prepare($args);
89 // NOTE: $this->auth_user has to get set in prepare(), not handle(),
90 // because subclasses do stuff with it in their prepares.
92 $oauthReq = $this->getOAuthRequest();
95 if ($this->requiresAuth()) {
96 $this->checkBasicAuthUser(true);
98 // Check to see if a basic auth user is there even
99 // if one's not required
100 $this->checkBasicAuthUser(false);
103 $this->checkOAuthRequest($oauthReq);
106 // NOTE: Make sure we're scoped properly based on the auths!
107 if (isset($this->auth_user) && !empty($this->auth_user)) {
108 $this->scoped = $this->auth_user->getProfile();
110 $this->scoped = null;
113 // Reject API calls with the wrong access level
115 if ($this->isReadOnly($args) == false) {
116 if ($this->access != self::READ_WRITE) {
117 // TRANS: Client error 401.
118 $msg = _('API resource requires read-write access, ' .
119 'but you only have read access.');
120 $this->clientError($msg, 401, $this->format);
129 * Determine whether the request is an OAuth request.
130 * This is to avoid doign any unnecessary DB lookups.
132 * @return mixed the OAuthRequest or false
134 function getOAuthRequest()
136 ApiOauthAction::cleanRequest();
138 $req = OAuthRequest::from_request();
140 $consumer = $req->get_parameter('oauth_consumer_key');
141 $accessToken = $req->get_parameter('oauth_token');
143 // XXX: Is it good enough to assume it's not meant to be an
144 // OAuth request if there is no consumer or token? --Z
146 if (empty($consumer) || empty($accessToken)) {
154 * Verifies the OAuth request signature, sets the auth user
155 * and access type (read-only or read-write)
157 * @param OAuthRequest $request the OAuth Request
161 function checkOAuthRequest($request)
163 $datastore = new ApiStatusNetOAuthDataStore();
164 $server = new OAuthServer($datastore);
165 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
167 $server->add_signature_method($hmac_method);
170 $server->verify_request($request);
172 $consumer = $request->get_parameter('oauth_consumer_key');
173 $access_token = $request->get_parameter('oauth_token');
175 $app = Oauth_application::getByConsumerKey($consumer);
180 'API OAuth - Couldn\'t find the OAuth app for consumer key: ' .
183 // TRANS: OAuth exception thrown when no application is found for a given consumer key.
184 throw new OAuthException(_('No application for that consumer key.'));
187 // set the source attr
188 if ($app->name != 'anonymous') {
189 $this->source = $app->name;
193 $appUser = Oauth_application_user::getKV('token', $access_token);
195 if (!empty($appUser)) {
196 // If access_type == 0 we have either a request token
197 // or a bad / revoked access token
199 if ($appUser->access_type != 0) {
200 // Set the access level for the api call
201 $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
202 ? self::READ_WRITE : self::READ_ONLY;
205 if (Event::handle('StartSetApiUser', array(&$user))) {
206 $user = User::getKV('id', $appUser->profile_id);
208 if (!$user->hasRight(Right::API)) {
209 // TRANS: Authorization exception thrown when a user without API access tries to access the API.
210 throw new AuthorizationException(_('Not allowed to use API.'));
213 $this->auth_user = $user;
214 // FIXME: setting the value returned by common_current_user()
215 // There should probably be a better method for this. common_set_user()
216 // does lots of session stuff.
218 $_cur = $this->auth_user;
219 Event::handle('EndSetApiUser', array($user));
222 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
223 "application '%s' (id: %d) with %s access.";
229 $this->auth_user->nickname,
230 $this->auth_user->id,
233 ($this->access = self::READ_WRITE) ? 'read-write' : 'read-only'
237 // TRANS: OAuth exception given when an incorrect access token was given for a user.
238 throw new OAuthException(_('Bad access token.'));
241 // Also should not happen.
242 // TRANS: OAuth exception given when no user was found for a given token (no token was found).
243 throw new OAuthException(_('No user for that token.'));
246 } catch (OAuthException $e) {
247 $this->logAuthFailure($e->getMessage());
248 common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
249 $this->clientError($e->getMessage(), 401, $this->format);
255 * Does this API resource require authentication?
257 * @return boolean true
259 function requiresAuth()
265 * Check for a user specified via HTTP basic auth. If there isn't
266 * one, try to get one by outputting the basic auth header.
268 * @return boolean true or false
270 function checkBasicAuthUser($required = true)
272 $this->basicAuthProcessHeader();
274 $realm = common_config('api', 'realm');
277 $realm = common_config('site', 'name') . ' API';
280 if (empty($this->auth_user_nickname) && $required) {
281 header('WWW-Authenticate: Basic realm="' . $realm . '"');
283 // show error if the user clicks 'cancel'
284 // TRANS: Client error thrown when authentication fails becaus a user clicked "Cancel".
285 $this->clientError(_('Could not authenticate you.'), 401, $this->format);
290 $user = common_check_user($this->auth_user_nickname,
291 $this->auth_user_password);
293 if (Event::handle('StartSetApiUser', array(&$user))) {
296 if (!$user->hasRight(Right::API)) {
297 // TRANS: Authorization exception thrown when a user without API access tries to access the API.
298 throw new AuthorizationException(_('Not allowed to use API.'));
300 $this->auth_user = $user;
303 Event::handle('EndSetApiUser', array($user));
306 // By default, basic auth users have rw access
307 $this->access = self::READ_WRITE;
309 if (empty($this->auth_user) && ($required || isset($_SERVER['PHP_AUTH_USER']))) {
311 "basic auth nickname = %s",
312 $this->auth_user_nickname
314 $this->logAuthFailure($msg);
315 // TRANS: Client error thrown when authentication fails.
316 $this->clientError(_('Could not authenticate you.'), 401, $this->format);
323 * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
324 * param to support basic auth when PHP is running in CGI mode.
328 function basicAuthProcessHeader()
330 $authHeaders = array('AUTHORIZATION',
331 'HTTP_AUTHORIZATION',
332 'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
333 $authorization_header = null;
334 foreach ($authHeaders as $header) {
335 if (isset($_SERVER[$header])) {
336 $authorization_header = $_SERVER[$header];
341 if (isset($_SERVER['PHP_AUTH_USER'])) {
342 $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
343 $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
344 } elseif (isset($authorization_header)
345 && strstr(substr($authorization_header, 0, 5), 'Basic')) {
347 // Decode the HTTP_AUTHORIZATION header on php-cgi server self
348 // on fcgid server the header name is AUTHORIZATION
349 $auth_hash = base64_decode(substr($authorization_header, 6));
350 list($this->auth_user_nickname,
351 $this->auth_user_password) = explode(':', $auth_hash);
353 // Set all to null on a empty basic auth request
355 if (empty($this->auth_user_nickname)) {
356 $this->auth_user_nickname = null;
357 $this->auth_password = null;
363 * Log an API authentication failure. Collect the proxy and IP
366 * @param string $logMsg additional log message
368 function logAuthFailure($logMsg)
370 list($proxy, $ip) = common_client_ip();
373 'API auth failure (proxy = %1$s, ip = %2$s) - ',
378 common_log(LOG_WARNING, $msg . $logMsg);