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 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
34 * @link http://status.net/
37 if (!defined('STATUSNET')) {
41 require_once INSTALLDIR . '/lib/api.php';
42 require_once INSTALLDIR . '/lib/apioauth.php';
45 * Actions extending this class will require auth
49 * @author Zach Copley <zach@status.net>
50 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
51 * @link http://status.net/
54 class ApiAuthAction extends ApiAction
56 var $auth_user_nickname = null;
57 var $auth_user_password = null;
60 * Take arguments for running, looks for an OAuth request,
61 * and outputs basic auth header if needed
63 * @param array $args $_REQUEST args
65 * @return boolean success flag
69 function prepare($args)
71 parent::prepare($args);
73 // NOTE: $this->auth_user has to get set in prepare(), not handle(),
74 // because subclasses do stuff with it in their prepares.
76 if ($this->requiresAuth()) {
78 $oauthReq = $this->getOAuthRequest();
81 $this->checkBasicAuthUser(true);
83 $this->checkOAuthRequest($oauthReq);
87 // Check to see if a basic auth user is there even
88 // if one's not required
89 $this->checkBasicAuthUser(false);
92 // Reject API calls with the wrong access level
94 if ($this->isReadOnly($args) == false) {
96 common_debug(get_class($this) . ' is not read-only!');
98 if ($this->access != self::READ_WRITE) {
99 $msg = _('API resource requires read-write access, ' .
100 'but you only have read access.');
101 $this->clientError($msg, 401, $this->format);
110 * Determine whether the request is an OAuth request.
111 * This is to avoid doign any unnecessary DB lookups.
113 * @return mixed the OAuthRequest or false
117 function getOAuthRequest()
119 ApiOauthAction::cleanRequest();
121 $req = OAuthRequest::from_request();
123 $consumer = $req->get_parameter('oauth_consumer_key');
124 $accessToken = $req->get_parameter('oauth_token');
126 // XXX: Is it good enough to assume it's not meant to be an
127 // OAuth request if there is no consumer or token? --Z
129 if (empty($consumer) || empty($accessToken)) {
137 * Verifies the OAuth request signature, sets the auth user
138 * and access type (read-only or read-write)
140 * @param OAuthRequest $request the OAuth Request
146 function checkOAuthRequest($request)
148 $datastore = new ApiStatusNetOAuthDataStore();
149 $server = new OAuthServer($datastore);
150 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
152 $server->add_signature_method($hmac_method);
156 $server->verify_request($request);
158 $consumer = $request->get_parameter('oauth_consumer_key');
159 $access_token = $request->get_parameter('oauth_token');
161 $app = Oauth_application::getByConsumerKey($consumer);
164 common_log(LOG_WARNING,
165 'Couldn\'t find the OAuth app for consumer key: ' .
167 throw new OAuthException('No application for that consumer key.');
170 // set the source attr
172 $this->oauth_source = $app->name;
174 $appUser = Oauth_application_user::staticGet('token', $access_token);
176 if (!empty($appUser)) {
178 // If access_type == 0 we have either a request token
179 // or a bad / revoked access token
181 if ($appUser->access_type != 0) {
183 // Set the access level for the api call
185 $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
186 ? self::READ_WRITE : self::READ_ONLY;
190 if (Event::handle('StartSetApiUser', array(&$user))) {
191 $this->auth_user = User::staticGet('id', $appUser->profile_id);
192 Event::handle('EndSetApiUser', array($user));
195 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
196 "application '%s' (id: %d) with %s access.";
198 common_log(LOG_INFO, sprintf($msg,
199 $this->auth_user->nickname,
200 $this->auth_user->id,
203 ($this->access = self::READ_WRITE) ?
204 'read-write' : 'read-only'
207 throw new OAuthException('Bad access token.');
211 // Also should not happen
213 throw new OAuthException('No user for that token.');
216 } catch (OAuthException $e) {
217 common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
218 $this->showAuthError();
224 * Does this API resource require authentication?
226 * @return boolean true
229 function requiresAuth()
235 * Check for a user specified via HTTP basic auth. If there isn't
236 * one, try to get one by outputting the basic auth header.
238 * @return boolean true or false
241 function checkBasicAuthUser($required = true)
243 $this->basicAuthProcessHeader();
245 $realm = common_config('site', 'name') . ' API';
247 if (!isset($this->auth_user_nickname) && $required) {
248 header('WWW-Authenticate: Basic realm="' . $realm . '"');
250 // show error if the user clicks 'cancel'
252 $this->showAuthError();
257 $user = common_check_user($this->auth_user_nickname,
258 $this->auth_user_password);
260 if (Event::handle('StartSetApiUser', array(&$user))) {
263 $this->auth_user = $user;
266 Event::handle('EndSetApiUser', array($user));
269 // By default, basic auth users have rw access
271 $this->access = self::READ_WRITE;
273 if (empty($this->auth_user) && $required) {
275 // basic authentication failed
277 list($proxy, $ip) = common_client_ip();
279 $msg = sprintf(_('Failed API auth attempt, nickname = %1$s, ' .
280 'proxy = %2$s, ip = %3$s'),
281 $this->auth_user_nickname,
284 common_log(LOG_WARNING, $msg);
285 $this->showAuthError();
292 * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
293 * param to support basic auth when PHP is running in CGI mode.
298 function basicAuthProcessHeader()
300 if (isset($_SERVER['AUTHORIZATION'])
301 || isset($_SERVER['HTTP_AUTHORIZATION'])
303 $authorization_header = isset($_SERVER['HTTP_AUTHORIZATION'])
304 ? $_SERVER['HTTP_AUTHORIZATION'] : $_SERVER['AUTHORIZATION'];
307 if (isset($_SERVER['PHP_AUTH_USER'])) {
308 $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
309 $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
310 } elseif (isset($authorization_header)
311 && strstr(substr($authorization_header, 0, 5), 'Basic')) {
313 // Decode the HTTP_AUTHORIZATION header on php-cgi server self
314 // on fcgid server the header name is AUTHORIZATION
316 $auth_hash = base64_decode(substr($authorization_header, 6));
317 list($this->auth_user_nickname,
318 $this->auth_user_password) = explode(':', $auth_hash);
320 // Set all to null on a empty basic auth request
322 if (empty($this->auth_user_nickname)) {
323 $this->auth_user_nickname = null;
324 $this->auth_password = null;
330 * Output an authentication error message. Use XML or JSON if one
331 * of those formats is specified, otherwise output plain text
336 function showAuthError()
338 header('HTTP/1.1 401 Unauthorized');
339 $msg = 'Could not authenticate you.';
341 if ($this->format == 'xml') {
342 header('Content-Type: application/xml; charset=utf-8');
344 $this->elementStart('hash');
345 $this->element('error', null, $msg);
346 $this->element('request', null, $_SERVER['REQUEST_URI']);
347 $this->elementEnd('hash');
349 } elseif ($this->format == 'json') {
350 header('Content-Type: application/json; charset=utf-8');
351 $error_array = array('error' => $msg,
352 'request' => $_SERVER['REQUEST_URI']);
353 print(json_encode($error_array));
355 header('Content-type: text/plain');