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/
72 class ApiAuthAction extends ApiAction
74 var $auth_user_nickname = null;
75 var $auth_user_password = null;
78 * Take arguments for running, looks for an OAuth request,
79 * and outputs basic auth header if needed
81 * @param array $args $_REQUEST args
83 * @return boolean success flag
87 function prepare($args)
89 parent::prepare($args);
91 // NOTE: $this->auth_user has to get set in prepare(), not handle(),
92 // because subclasses do stuff with it in their prepares.
94 $oauthReq = $this->getOAuthRequest();
97 if ($this->requiresAuth()) {
98 $this->checkBasicAuthUser(true);
100 // Check to see if a basic auth user is there even
101 // if one's not required
102 $this->checkBasicAuthUser(false);
105 $this->checkOAuthRequest($oauthReq);
108 // Reject API calls with the wrong access level
110 if ($this->isReadOnly($args) == false) {
111 if ($this->access != self::READ_WRITE) {
112 // TRANS: Client error 401.
113 $msg = _('API resource requires read-write access, ' .
114 'but you only have read access.');
115 $this->clientError($msg, 401, $this->format);
124 * Determine whether the request is an OAuth request.
125 * This is to avoid doign any unnecessary DB lookups.
127 * @return mixed the OAuthRequest or false
130 function getOAuthRequest()
132 ApiOauthAction::cleanRequest();
134 $req = OAuthRequest::from_request();
136 $consumer = $req->get_parameter('oauth_consumer_key');
137 $accessToken = $req->get_parameter('oauth_token');
139 // XXX: Is it good enough to assume it's not meant to be an
140 // OAuth request if there is no consumer or token? --Z
142 if (empty($consumer) || empty($accessToken)) {
150 * Verifies the OAuth request signature, sets the auth user
151 * and access type (read-only or read-write)
153 * @param OAuthRequest $request the OAuth Request
158 function checkOAuthRequest($request)
160 $datastore = new ApiStatusNetOAuthDataStore();
161 $server = new OAuthServer($datastore);
162 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
164 $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);
176 common_log(LOG_WARNING,
177 'Couldn\'t find the OAuth app for consumer key: ' .
179 throw new OAuthException('No application for that consumer key.');
182 // set the source attr
184 $this->source = $app->name;
186 $appUser = Oauth_application_user::staticGet('token', $access_token);
188 if (!empty($appUser)) {
190 // If access_type == 0 we have either a request token
191 // or a bad / revoked access token
193 if ($appUser->access_type != 0) {
195 // Set the access level for the api call
197 $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
198 ? self::READ_WRITE : self::READ_ONLY;
202 if (Event::handle('StartSetApiUser', array(&$user))) {
203 $this->auth_user = User::staticGet('id', $appUser->profile_id);
204 Event::handle('EndSetApiUser', array($user));
207 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
208 "application '%s' (id: %d) with %s access.";
210 common_log(LOG_INFO, sprintf($msg,
211 $this->auth_user->nickname,
212 $this->auth_user->id,
215 ($this->access = self::READ_WRITE) ?
216 'read-write' : 'read-only'
219 throw new OAuthException('Bad access token.');
223 // Also should not happen
225 throw new OAuthException('No user for that token.');
228 } catch (OAuthException $e) {
229 common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
230 $this->clientError($e->getMessage(), 401, $this->format);
236 * Does this API resource require authentication?
238 * @return boolean true
241 function requiresAuth()
247 * Check for a user specified via HTTP basic auth. If there isn't
248 * one, try to get one by outputting the basic auth header.
250 * @return boolean true or false
253 function checkBasicAuthUser($required = true)
255 $this->basicAuthProcessHeader();
257 $realm = common_config('api', 'realm');
260 $realm = common_config('site', 'name') . ' API';
263 if (empty($this->auth_user_nickname) && $required) {
264 header('WWW-Authenticate: Basic realm="' . $realm . '"');
266 // show error if the user clicks 'cancel'
268 $this->clientError("Could not authenticate you.", 401, $this->format);
273 $user = common_check_user($this->auth_user_nickname,
274 $this->auth_user_password);
276 if (Event::handle('StartSetApiUser', array(&$user))) {
279 $this->auth_user = $user;
282 Event::handle('EndSetApiUser', array($user));
285 // By default, basic auth users have rw access
287 $this->access = self::READ_WRITE;
289 if (empty($this->auth_user) && ($required || isset($_SERVER['PHP_AUTH_USER']))) {
291 // basic authentication failed
293 list($proxy, $ip) = common_client_ip();
295 $msg = sprintf( 'Failed API auth attempt, nickname = %1$s, ' .
296 'proxy = %2$s, ip = %3$s',
297 $this->auth_user_nickname,
300 common_log(LOG_WARNING, $msg);
301 $this->clientError("Could not authenticate you.", 401, $this->format);
308 * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
309 * param to support basic auth when PHP is running in CGI mode.
314 function basicAuthProcessHeader()
316 $authHeaders = array('AUTHORIZATION',
317 'HTTP_AUTHORIZATION',
318 'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
319 $authorization_header = null;
320 foreach ($authHeaders as $header) {
321 if (isset($_SERVER[$header])) {
322 $authorization_header = $_SERVER[$header];
327 if (isset($_SERVER['PHP_AUTH_USER'])) {
328 $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
329 $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
330 } elseif (isset($authorization_header)
331 && strstr(substr($authorization_header, 0, 5), 'Basic')) {
333 // Decode the HTTP_AUTHORIZATION header on php-cgi server self
334 // on fcgid server the header name is AUTHORIZATION
336 $auth_hash = base64_decode(substr($authorization_header, 6));
337 list($this->auth_user_nickname,
338 $this->auth_user_password) = explode(':', $auth_hash);
340 // Set all to null on a empty basic auth request
342 if (empty($this->auth_user_nickname)) {
343 $this->auth_user_nickname = null;
344 $this->auth_password = null;