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('GNUSOCIAL')) { exit(1); }
59 * Actions extending this class will require auth
63 * @author Zach Copley <zach@status.net>
64 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
65 * @link http://status.net/
67 class ApiAuthAction extends ApiAction
69 var $auth_user_nickname = null;
70 var $auth_user_password = null;
73 * Take arguments for running, looks for an OAuth request,
74 * and outputs basic auth header if needed
76 * @param array $args $_REQUEST args
78 * @return boolean success flag
81 protected function prepare(array $args=array())
83 parent::prepare($args);
85 // NOTE: $this->auth_user has to get set in prepare(), not handle(),
86 // because subclasses do stuff with it in their prepares.
88 $oauthReq = $this->getOAuthRequest();
91 if ($this->requiresAuth()) {
92 $this->checkBasicAuthUser(true);
94 // Check to see if a basic auth user is there even
95 // if one's not required
96 $this->checkBasicAuthUser(false);
99 $this->checkOAuthRequest($oauthReq);
102 // NOTE: Make sure we're scoped properly based on the auths!
103 if (isset($this->auth_user) && !empty($this->auth_user)) {
104 $this->scoped = $this->auth_user->getProfile();
106 $this->scoped = null;
109 // Reject API calls with the wrong access level
111 if ($this->isReadOnly($args) == false) {
112 if ($this->access != self::READ_WRITE) {
113 // TRANS: Client error 401.
114 $msg = _('API resource requires read-write access, ' .
115 'but you only have read access.');
116 $this->clientError($msg, 401, $this->format);
125 * Determine whether the request is an OAuth request.
126 * This is to avoid doign any unnecessary DB lookups.
128 * @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
157 function checkOAuthRequest($request)
159 $datastore = new ApiGNUSocialOAuthDataStore();
160 $server = new OAuthServer($datastore);
161 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
163 $server->add_signature_method($hmac_method);
166 $server->verify_request($request);
168 $consumer = $request->get_parameter('oauth_consumer_key');
169 $access_token = $request->get_parameter('oauth_token');
171 $app = Oauth_application::getByConsumerKey($consumer);
176 'API OAuth - Couldn\'t find the OAuth app for consumer key: ' .
179 // TRANS: OAuth exception thrown when no application is found for a given consumer key.
180 throw new OAuthException(_('No application for that consumer key.'));
183 // set the source attr
184 if ($app->name != 'anonymous') {
185 $this->source = $app->name;
189 $appUser = Oauth_application_user::getKV('token', $access_token);
191 if (!empty($appUser)) {
192 // If access_type == 0 we have either a request token
193 // or a bad / revoked access token
195 if ($appUser->access_type != 0) {
196 // Set the access level for the api call
197 $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
198 ? self::READ_WRITE : self::READ_ONLY;
201 if (Event::handle('StartSetApiUser', array(&$user))) {
202 $user = User::getKV('id', $appUser->profile_id);
204 if (!$user->hasRight(Right::API)) {
205 // TRANS: Authorization exception thrown when a user without API access tries to access the API.
206 throw new AuthorizationException(_('Not allowed to use API.'));
209 $this->auth_user = $user;
210 // FIXME: setting the value returned by common_current_user()
211 // There should probably be a better method for this. common_set_user()
212 // does lots of session stuff.
214 $_cur = $this->auth_user;
215 Event::handle('EndSetApiUser', array($user));
218 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
219 "application '%s' (id: %d) with %s access.";
225 $this->auth_user->nickname,
226 $this->auth_user->id,
229 ($this->access = self::READ_WRITE) ? 'read-write' : 'read-only'
233 // TRANS: OAuth exception given when an incorrect access token was given for a user.
234 throw new OAuthException(_('Bad access token.'));
237 // Also should not happen.
238 // TRANS: OAuth exception given when no user was found for a given token (no token was found).
239 throw new OAuthException(_('No user for that token.'));
242 } catch (OAuthException $e) {
243 $this->logAuthFailure($e->getMessage());
244 common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
245 $this->clientError($e->getMessage(), 401, $this->format);
251 * Does this API resource require authentication?
253 * @return boolean true
255 function requiresAuth()
261 * Check for a user specified via HTTP basic auth. If there isn't
262 * one, try to get one by outputting the basic auth header.
264 * @return boolean true or false
266 function checkBasicAuthUser($required = true)
268 $this->basicAuthProcessHeader();
270 $realm = common_config('api', 'realm');
273 $realm = common_config('site', 'name') . ' API';
276 if (empty($this->auth_user_nickname) && $required) {
277 header('WWW-Authenticate: Basic realm="' . $realm . '"');
279 // show error if the user clicks 'cancel'
280 // TRANS: Client error thrown when authentication fails becaus a user clicked "Cancel".
281 $this->clientError(_('Could not authenticate you.'), 401, $this->format);
286 $user = common_check_user($this->auth_user_nickname,
287 $this->auth_user_password);
289 if (Event::handle('StartSetApiUser', array(&$user))) {
292 if (!$user->hasRight(Right::API)) {
293 // TRANS: Authorization exception thrown when a user without API access tries to access the API.
294 throw new AuthorizationException(_('Not allowed to use API.'));
296 $this->auth_user = $user;
299 Event::handle('EndSetApiUser', array($user));
302 // By default, basic auth users have rw access
303 $this->access = self::READ_WRITE;
305 if (empty($this->auth_user) && ($required || isset($_SERVER['PHP_AUTH_USER']))) {
307 "basic auth nickname = %s",
308 $this->auth_user_nickname
310 $this->logAuthFailure($msg);
311 // TRANS: Client error thrown when authentication fails.
312 $this->clientError(_('Could not authenticate you.'), 401, $this->format);
319 * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
320 * param to support basic auth when PHP is running in CGI mode.
324 function basicAuthProcessHeader()
326 $authHeaders = array('AUTHORIZATION',
327 'HTTP_AUTHORIZATION',
328 'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
329 $authorization_header = null;
330 foreach ($authHeaders as $header) {
331 if (isset($_SERVER[$header])) {
332 $authorization_header = $_SERVER[$header];
337 if (isset($_SERVER['PHP_AUTH_USER'])) {
338 $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
339 $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
340 } elseif (isset($authorization_header)
341 && strstr(substr($authorization_header, 0, 5), 'Basic')) {
343 // Decode the HTTP_AUTHORIZATION header on php-cgi server self
344 // on fcgid server the header name is AUTHORIZATION
345 $auth_hash = base64_decode(substr($authorization_header, 6));
346 list($this->auth_user_nickname,
347 $this->auth_user_password) = explode(':', $auth_hash);
349 // Set all to null on a empty basic auth request
351 if (empty($this->auth_user_nickname)) {
352 $this->auth_user_nickname = null;
353 $this->auth_password = null;
359 * Log an API authentication failure. Collect the proxy and IP
362 * @param string $logMsg additional log message
364 function logAuthFailure($logMsg)
366 list($proxy, $ip) = common_client_ip();
369 'API auth failure (proxy = %1$s, ip = %2$s) - ',
374 common_log(LOG_WARNING, $msg . $logMsg);