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')) {
61 * Actions extending this class will require auth
65 * @author Zach Copley <zach@status.net>
66 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
67 * @link http://status.net/
69 class ApiAuthAction extends ApiAction
71 var $auth_user_nickname = null;
72 var $auth_user_password = null;
75 * Take arguments for running, looks for an OAuth request,
76 * and outputs basic auth header if needed
78 * @param array $args $_REQUEST args
80 * @return boolean success flag
83 function prepare($args)
85 parent::prepare($args);
87 // NOTE: $this->auth_user has to get set in prepare(), not handle(),
88 // because subclasses do stuff with it in their prepares.
90 $oauthReq = $this->getOAuthRequest();
93 if ($this->requiresAuth()) {
94 $this->checkBasicAuthUser(true);
96 // Check to see if a basic auth user is there even
97 // if one's not required
98 $this->checkBasicAuthUser(false);
101 $this->checkOAuthRequest($oauthReq);
104 // NOTE: Make sure we're scoped properly based on the auths!
105 if (isset($this->auth_user) && !empty($this->auth_user)) {
106 $this->scoped = $this->auth_user->getProfile();
108 $this->scoped = null;
111 // Reject API calls with the wrong access level
113 if ($this->isReadOnly($args) == false) {
114 if ($this->access != self::READ_WRITE) {
115 // TRANS: Client error 401.
116 $msg = _('API resource requires read-write access, ' .
117 'but you only have read access.');
118 $this->clientError($msg, 401, $this->format);
127 * Determine whether the request is an OAuth request.
128 * This is to avoid doign any unnecessary DB lookups.
130 * @return mixed the OAuthRequest or false
132 function getOAuthRequest()
134 ApiOAuthAction::cleanRequest();
136 $req = OAuthRequest::from_request();
138 $consumer = $req->get_parameter('oauth_consumer_key');
139 $accessToken = $req->get_parameter('oauth_token');
141 // XXX: Is it good enough to assume it's not meant to be an
142 // OAuth request if there is no consumer or token? --Z
144 if (empty($consumer) || empty($accessToken)) {
152 * Verifies the OAuth request signature, sets the auth user
153 * and access type (read-only or read-write)
155 * @param OAuthRequest $request the OAuth Request
159 function checkOAuthRequest($request)
161 $datastore = new ApiGNUSocialOAuthDataStore();
162 $server = new OAuthServer($datastore);
163 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
165 $server->add_signature_method($hmac_method);
168 $server->verify_request($request);
170 $consumer = $request->get_parameter('oauth_consumer_key');
171 $access_token = $request->get_parameter('oauth_token');
173 $app = Oauth_application::getByConsumerKey($consumer);
178 'API OAuth - Couldn\'t find the OAuth app for consumer key: ' .
181 // TRANS: OAuth exception thrown when no application is found for a given consumer key.
182 throw new OAuthException(_('No application for that consumer key.'));
185 // set the source attr
186 if ($app->name != 'anonymous') {
187 $this->source = $app->name;
191 $appUser = Oauth_application_user::getKV('token', $access_token);
193 if (!empty($appUser)) {
194 // If access_type == 0 we have either a request token
195 // or a bad / revoked access token
197 if ($appUser->access_type != 0) {
198 // Set the access level for the api call
199 $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
200 ? self::READ_WRITE : self::READ_ONLY;
203 if (Event::handle('StartSetApiUser', array(&$user))) {
204 $user = User::getKV('id', $appUser->profile_id);
206 if (!$user->hasRight(Right::API)) {
207 // TRANS: Authorization exception thrown when a user without API access tries to access the API.
208 throw new AuthorizationException(_('Not allowed to use API.'));
211 $this->auth_user = $user;
212 // FIXME: setting the value returned by common_current_user()
213 // There should probably be a better method for this. common_set_user()
214 // does lots of session stuff.
216 $_cur = $this->auth_user;
217 Event::handle('EndSetApiUser', array($user));
220 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
221 "application '%s' (id: %d) with %s access.";
227 $this->auth_user->nickname,
228 $this->auth_user->id,
231 ($this->access = self::READ_WRITE) ? 'read-write' : 'read-only'
235 // TRANS: OAuth exception given when an incorrect access token was given for a user.
236 throw new OAuthException(_('Bad access token.'));
239 // Also should not happen.
240 // TRANS: OAuth exception given when no user was found for a given token (no token was found).
241 throw new OAuthException(_('No user for that token.'));
244 } catch (OAuthException $e) {
245 $this->logAuthFailure($e->getMessage());
246 common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
247 $this->clientError($e->getMessage(), 401, $this->format);
253 * Does this API resource require authentication?
255 * @return boolean true
257 function requiresAuth()
263 * Check for a user specified via HTTP basic auth. If there isn't
264 * one, try to get one by outputting the basic auth header.
266 * @return boolean true or false
268 function checkBasicAuthUser($required = true)
270 $this->basicAuthProcessHeader();
272 $realm = common_config('api', 'realm');
275 $realm = common_config('site', 'name') . ' API';
278 if (empty($this->auth_user_nickname) && $required) {
279 header('WWW-Authenticate: Basic realm="' . $realm . '"');
281 // show error if the user clicks 'cancel'
282 // TRANS: Client error thrown when authentication fails becaus a user clicked "Cancel".
283 $this->clientError(_('Could not authenticate you.'), 401, $this->format);
288 $user = common_check_user($this->auth_user_nickname,
289 $this->auth_user_password);
291 if (Event::handle('StartSetApiUser', array(&$user))) {
294 if (!$user->hasRight(Right::API)) {
295 // TRANS: Authorization exception thrown when a user without API access tries to access the API.
296 throw new AuthorizationException(_('Not allowed to use API.'));
298 $this->auth_user = $user;
301 Event::handle('EndSetApiUser', array($user));
304 // By default, basic auth users have rw access
305 $this->access = self::READ_WRITE;
307 if (empty($this->auth_user) && ($required || isset($_SERVER['PHP_AUTH_USER']))) {
309 "basic auth nickname = %s",
310 $this->auth_user_nickname
312 $this->logAuthFailure($msg);
313 // TRANS: Client error thrown when authentication fails.
314 $this->clientError(_('Could not authenticate you.'), 401, $this->format);
321 * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
322 * param to support basic auth when PHP is running in CGI mode.
326 function basicAuthProcessHeader()
328 $authHeaders = array('AUTHORIZATION',
329 'HTTP_AUTHORIZATION',
330 'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
331 $authorization_header = null;
332 foreach ($authHeaders as $header) {
333 if (isset($_SERVER[$header])) {
334 $authorization_header = $_SERVER[$header];
339 if (isset($_SERVER['PHP_AUTH_USER'])) {
340 $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
341 $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
342 } elseif (isset($authorization_header)
343 && strstr(substr($authorization_header, 0, 5), 'Basic')) {
345 // Decode the HTTP_AUTHORIZATION header on php-cgi server self
346 // on fcgid server the header name is AUTHORIZATION
347 $auth_hash = base64_decode(substr($authorization_header, 6));
348 list($this->auth_user_nickname,
349 $this->auth_user_password) = explode(':', $auth_hash);
351 // Set all to null on a empty basic auth request
353 if (empty($this->auth_user_nickname)) {
354 $this->auth_user_nickname = null;
355 $this->auth_password = null;
361 * Log an API authentication failure. Collect the proxy and IP
364 * @param string $logMsg additional log message
366 function logAuthFailure($logMsg)
368 list($proxy, $ip) = common_client_ip();
371 'API auth failure (proxy = %1$s, ip = %2$s) - ',
376 common_log(LOG_WARNING, $msg . $logMsg);