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;
58 var $access_token = null;
59 var $oauth_source = null;
62 * Take arguments for running, and output basic auth header if needed
64 * @param array $args $_REQUEST args
66 * @return boolean success flag
70 function prepare($args)
72 parent::prepare($args);
74 $this->consumer_key = $this->arg('oauth_consumer_key');
75 $this->access_token = $this->arg('oauth_token');
77 // NOTE: $this->auth_user has to get set in prepare(), not handle(),
78 // because subclasses do stuff with it in their prepares.
80 if ($this->requiresAuth()) {
81 if (!empty($this->access_token)) {
82 $this->checkOAuthRequest();
84 $this->checkBasicAuthUser(true);
88 // Check to see if a basic auth user is there even
89 // if one's not required
91 if (empty($this->access_token)) {
92 $this->checkBasicAuthUser(false);
96 // Reject API calls with the wrong access level
98 if ($this->isReadOnly($args) == false) {
99 if ($this->access != self::READ_WRITE) {
100 $msg = _('API resource requires read-write access, ' .
101 'but you only have read access.');
102 $this->clientError($msg, 401, $this->format);
110 function handle($args)
112 parent::handle($args);
115 function checkOAuthRequest()
117 $datastore = new ApiStatusNetOAuthDataStore();
118 $server = new OAuthServer($datastore);
119 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
121 $server->add_signature_method($hmac_method);
123 ApiOauthAction::cleanRequest();
127 $req = OAuthRequest::from_request();
128 $server->verify_request($req);
130 $app = Oauth_application::getByConsumerKey($this->consumer_key);
134 // this should probably not happen
135 common_log(LOG_WARNING,
136 'Couldn\'t find the OAuth app for consumer key: ' .
137 $this->consumer_key);
139 throw new OAuthException('No application for that consumer key.');
142 // set the source attr
144 $this->oauth_source = $app->name;
146 $appUser = Oauth_application_user::staticGet('token',
147 $this->access_token);
149 // XXX: Check that app->id and appUser->application_id and consumer all
152 if (!empty($appUser)) {
154 // If access_type == 0 we have either a request token
155 // or a bad / revoked access token
157 if ($appUser->access_type != 0) {
159 // Set the access level for the api call
161 $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
162 ? self::READ_WRITE : self::READ_ONLY;
164 if (Event::handle('StartSetApiUser', array(&$user))) {
165 $this->auth_user = User::staticGet('id', $appUser->profile_id);
166 Event::handle('EndSetApiUser', array($user));
169 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
170 "application '%s' (id: %d) with %s access.";
172 common_log(LOG_INFO, sprintf($msg,
173 $this->auth_user->nickname,
174 $this->auth_user->id,
177 ($this->access = self::READ_WRITE) ?
178 'read-write' : 'read-only'
182 throw new OAuthException('Bad access token.');
186 // Also should not happen
188 throw new OAuthException('No user for that token.');
191 } catch (OAuthException $e) {
192 common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
193 $this->showAuthError();
199 * Does this API resource require authentication?
201 * @return boolean true
204 function requiresAuth()
210 * Check for a user specified via HTTP basic auth. If there isn't
211 * one, try to get one by outputting the basic auth header.
213 * @return boolean true or false
216 function checkBasicAuthUser($required = true)
218 $this->basicAuthProcessHeader();
220 $realm = common_config('site', 'name') . ' API';
222 if (!isset($this->auth_user_nickname) && $required) {
223 header('WWW-Authenticate: Basic realm="' . $realm . '"');
225 // show error if the user clicks 'cancel'
227 $this->showAuthError();
232 $user = common_check_user($this->auth_user_nickname,
233 $this->auth_user_password);
235 if (Event::handle('StartSetApiUser', array(&$user))) {
238 $this->auth_user = $user;
241 Event::handle('EndSetApiUser', array($user));
244 // By default, basic auth users have rw access
246 $this->access = self::READ_WRITE;
248 if (empty($this->auth_user) && $required) {
250 // basic authentication failed
252 list($proxy, $ip) = common_client_ip();
254 $msg = sprintf(_('Failed API auth attempt, nickname = %1$s, ' .
255 'proxy = %2$s, ip = %3$s'),
256 $this->auth_user_nickname,
259 common_log(LOG_WARNING, $msg);
260 $this->showAuthError();
267 * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
268 * param to support basic auth when PHP is running in CGI mode.
273 function basicAuthProcessHeader()
275 if (isset($_SERVER['AUTHORIZATION'])
276 || isset($_SERVER['HTTP_AUTHORIZATION'])
278 $authorization_header = isset($_SERVER['HTTP_AUTHORIZATION'])
279 ? $_SERVER['HTTP_AUTHORIZATION'] : $_SERVER['AUTHORIZATION'];
282 if (isset($_SERVER['PHP_AUTH_USER'])) {
283 $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
284 $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
285 } elseif (isset($authorization_header)
286 && strstr(substr($authorization_header, 0, 5), 'Basic')) {
288 // Decode the HTTP_AUTHORIZATION header on php-cgi server self
289 // on fcgid server the header name is AUTHORIZATION
291 $auth_hash = base64_decode(substr($authorization_header, 6));
292 list($this->auth_user_nickname,
293 $this->auth_user_password) = explode(':', $auth_hash);
295 // Set all to null on a empty basic auth request
297 if (empty($this->auth_user_nickname)) {
298 $this->auth_user_nickname = null;
299 $this->auth_password = null;
305 * Output an authentication error message. Use XML or JSON if one
306 * of those formats is specified, otherwise output plain text
311 function showAuthError()
313 header('HTTP/1.1 401 Unauthorized');
314 $msg = 'Could not authenticate you.';
316 if ($this->format == 'xml') {
317 header('Content-Type: application/xml; charset=utf-8');
319 $this->elementStart('hash');
320 $this->element('error', null, $msg);
321 $this->element('request', null, $_SERVER['REQUEST_URI']);
322 $this->elementEnd('hash');
324 } elseif ($this->format == 'json') {
325 header('Content-Type: application/json; charset=utf-8');
326 $error_array = array('error' => $msg,
327 'request' => $_SERVER['REQUEST_URI']);
328 print(json_encode($error_array));
330 header('Content-type: text/plain');