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 // Reject API calls with the wrong access level
108 if ($this->isReadOnly($args) == false) {
109 if ($this->access != self::READ_WRITE) {
110 // TRANS: Client error 401.
111 $msg = _('API resource requires read-write access, ' .
112 'but you only have read access.');
113 $this->clientError($msg, 401, $this->format);
122 * Determine whether the request is an OAuth request.
123 * This is to avoid doign any unnecessary DB lookups.
125 * @return mixed the OAuthRequest or false
127 function getOAuthRequest()
129 ApiOauthAction::cleanRequest();
131 $req = OAuthRequest::from_request();
133 $consumer = $req->get_parameter('oauth_consumer_key');
134 $accessToken = $req->get_parameter('oauth_token');
136 // XXX: Is it good enough to assume it's not meant to be an
137 // OAuth request if there is no consumer or token? --Z
139 if (empty($consumer) || empty($accessToken)) {
147 * Verifies the OAuth request signature, sets the auth user
148 * and access type (read-only or read-write)
150 * @param OAuthRequest $request the OAuth Request
154 function checkOAuthRequest($request)
156 $datastore = new ApiStatusNetOAuthDataStore();
157 $server = new OAuthServer($datastore);
158 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
160 $server->add_signature_method($hmac_method);
163 $server->verify_request($request);
165 $consumer = $request->get_parameter('oauth_consumer_key');
166 $access_token = $request->get_parameter('oauth_token');
168 $app = Oauth_application::getByConsumerKey($consumer);
173 'API OAuth - Couldn\'t find the OAuth app for consumer key: ' .
176 // TRANS: OAuth exception thrown when no application is found for a given consumer key.
177 throw new OAuthException(_('No application for that consumer key.'));
180 // set the source attr
181 if ($app->name != 'anonymous') {
182 $this->source = $app->name;
186 $appUser = Oauth_application_user::staticGet('token', $access_token);
188 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) {
193 // Set the access level for the api call
194 $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
195 ? self::READ_WRITE : self::READ_ONLY;
198 if (Event::handle('StartSetApiUser', array(&$user))) {
199 $user = User::staticGet('id', $appUser->profile_id);
201 if (!$user->hasRight(Right::API)) {
202 // TRANS: Authorization exception thrown when a user without API access tries to access the API.
203 throw new AuthorizationException(_('Not allowed to use API.'));
206 $this->auth_user = $user;
207 // FIXME: setting the value returned by common_current_user()
208 // There should probably be a better method for this. common_set_user()
209 // does lots of session stuff.
211 $_cur = $this->auth_user;
212 Event::handle('EndSetApiUser', array($user));
215 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
216 "application '%s' (id: %d) with %s access.";
222 $this->auth_user->nickname,
223 $this->auth_user->id,
226 ($this->access = self::READ_WRITE) ? 'read-write' : 'read-only'
230 // TRANS: OAuth exception given when an incorrect access token was given for a user.
231 throw new OAuthException(_('Bad access token.'));
234 // Also should not happen.
235 // TRANS: OAuth exception given when no user was found for a given token (no token was found).
236 throw new OAuthException(_('No user for that token.'));
239 } catch (OAuthException $e) {
240 $this->logAuthFailure($e->getMessage());
241 common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
242 $this->clientError($e->getMessage(), 401, $this->format);
248 * Does this API resource require authentication?
250 * @return boolean true
252 function requiresAuth()
258 * Check for a user specified via HTTP basic auth. If there isn't
259 * one, try to get one by outputting the basic auth header.
261 * @return boolean true or false
263 function checkBasicAuthUser($required = true)
265 $this->basicAuthProcessHeader();
267 $realm = common_config('api', 'realm');
270 $realm = common_config('site', 'name') . ' API';
273 if (empty($this->auth_user_nickname) && $required) {
274 header('WWW-Authenticate: Basic realm="' . $realm . '"');
276 // show error if the user clicks 'cancel'
277 // TRANS: Client error thrown when authentication fails becaus a user clicked "Cancel".
278 $this->clientError(_('Could not authenticate you.'), 401, $this->format);
283 $user = common_check_user($this->auth_user_nickname,
284 $this->auth_user_password);
286 if (Event::handle('StartSetApiUser', array(&$user))) {
289 if (!$user->hasRight(Right::API)) {
290 // TRANS: Authorization exception thrown when a user without API access tries to access the API.
291 throw new AuthorizationException(_('Not allowed to use API.'));
293 $this->auth_user = $user;
296 Event::handle('EndSetApiUser', array($user));
299 // By default, basic auth users have rw access
300 $this->access = self::READ_WRITE;
302 if (empty($this->auth_user) && ($required || isset($_SERVER['PHP_AUTH_USER']))) {
304 "basic auth nickname = %s",
305 $this->auth_user_nickname
307 $this->logAuthFailure($msg);
308 // TRANS: Client error thrown when authentication fails.
309 $this->clientError(_('Could not authenticate you.'), 401, $this->format);
316 * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
317 * param to support basic auth when PHP is running in CGI mode.
321 function basicAuthProcessHeader()
323 $authHeaders = array('AUTHORIZATION',
324 'HTTP_AUTHORIZATION',
325 'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
326 $authorization_header = null;
327 foreach ($authHeaders as $header) {
328 if (isset($_SERVER[$header])) {
329 $authorization_header = $_SERVER[$header];
334 if (isset($_SERVER['PHP_AUTH_USER'])) {
335 $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
336 $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
337 } elseif (isset($authorization_header)
338 && strstr(substr($authorization_header, 0, 5), 'Basic')) {
340 // Decode the HTTP_AUTHORIZATION header on php-cgi server self
341 // on fcgid server the header name is AUTHORIZATION
342 $auth_hash = base64_decode(substr($authorization_header, 6));
343 list($this->auth_user_nickname,
344 $this->auth_user_password) = explode(':', $auth_hash);
346 // Set all to null on a empty basic auth request
348 if (empty($this->auth_user_nickname)) {
349 $this->auth_user_nickname = null;
350 $this->auth_password = null;
356 * Log an API authentication failure. Collect the proxy and IP
359 * @param string $logMsg additional log message
361 function logAuthFailure($logMsg)
363 list($proxy, $ip) = common_client_ip();
366 'API auth failure (proxy = %1$s, ip = %2$s) - ',
371 common_log(LOG_WARNING, $msg . $logMsg);