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;
60 var $auth_user = null;
63 * Take arguments for running, and output basic auth header if needed
65 * @param array $args $_REQUEST args
67 * @return boolean success flag
71 function prepare($args)
73 parent::prepare($args);
75 $this->consumer_key = $this->arg('oauth_consumer_key');
76 $this->access_token = $this->arg('oauth_token');
78 // NOTE: $this->auth_user has to get set in prepare(), not handle(),
79 // because subclasses do stuff with it in their prepares.
81 if ($this->requiresAuth()) {
82 if (!empty($this->access_token)) {
83 $this->checkOAuthRequest();
85 $this->checkBasicAuthUser();
89 // Check to see if a basic auth user is there even
90 // if one's not required
92 $this->checkBasicAuthUser(false);
95 // Reject API calls with the wrong access level
97 if ($this->isReadOnly($args) == false) {
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);
109 function handle($args)
111 parent::handle($args);
114 function checkOAuthRequest()
116 $datastore = new ApiStatusNetOAuthDataStore();
117 $server = new OAuthServer($datastore);
118 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
120 $server->add_signature_method($hmac_method);
122 ApiOauthAction::cleanRequest();
126 $req = OAuthRequest::from_request();
127 $server->verify_request($req);
129 $app = Oauth_application::getByConsumerKey($this->consumer_key);
133 // this should probably not happen
134 common_log(LOG_WARNING,
135 'Couldn\'t find the OAuth app for consumer key: ' .
136 $this->consumer_key);
138 throw new OAuthException('No application for that consumer key.');
141 // set the source attr
143 $this->oauth_source = $app->name;
145 $appUser = Oauth_application_user::staticGet('token',
146 $this->access_token);
148 // XXX: Check that app->id and appUser->application_id and consumer all
151 if (!empty($appUser)) {
153 // If access_type == 0 we have either a request token
154 // or a bad / revoked access token
156 if ($appUser->access_type != 0) {
158 // Set the access level for the api call
160 $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
161 ? self::READ_WRITE : self::READ_ONLY;
163 if (Event::handle('StartSetApiUser', array(&$user))) {
164 $this->auth_user = User::staticGet('id', $appUser->profile_id);
165 Event::handle('EndSetApiUser', array($user));
168 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
169 "application '%s' (id: %d) with %s access.";
171 common_log(LOG_INFO, sprintf($msg,
172 $this->auth_user->nickname,
173 $this->auth_user->id,
176 ($this->access = self::READ_WRITE) ?
177 'read-write' : 'read-only'
181 throw new OAuthException('Bad access token.');
185 // Also should not happen
187 throw new OAuthException('No user for that token.');
190 } catch (OAuthException $e) {
191 common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
192 $this->showAuthError();
198 * Does this API resource require authentication?
200 * @return boolean true
203 function requiresAuth()
209 * Check for a user specified via HTTP basic auth. If there isn't
210 * one, try to get one by outputting the basic auth header.
212 * @return boolean true or false
215 function checkBasicAuthUser($required = true)
217 $this->basicAuthProcessHeader();
219 $realm = common_config('site', 'name') . ' API';
221 if (!isset($this->auth_user_nickname) && $required) {
222 header('WWW-Authenticate: Basic realm="' . $realm . '"');
224 // show error if the user clicks 'cancel'
226 $this->showAuthError();
231 if (Event::handle('StartSetApiUser', array(&$user))) {
232 $this->auth_user = common_check_user($this->auth_user_nickname,
233 $this->auth_user_password);
235 Event::handle('EndSetApiUser', array($user));
238 // By default, basic auth users have rw access
240 $this->access = self::READ_WRITE;
242 if (empty($this->auth_user)) {
244 // basic authentication failed
246 list($proxy, $ip) = common_client_ip();
250 'Failed API auth attempt, nickname = ' .
251 "$nickname, proxy = $proxy, ip = $ip."
254 $this->showAuthError();
261 * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
262 * param to support basic auth when PHP is running in CGI mode.
267 function basicAuthProcessHeader()
269 if (isset($_SERVER['AUTHORIZATION'])
270 || isset($_SERVER['HTTP_AUTHORIZATION'])
272 $authorization_header = isset($_SERVER['HTTP_AUTHORIZATION'])
273 ? $_SERVER['HTTP_AUTHORIZATION'] : $_SERVER['AUTHORIZATION'];
276 if (isset($_SERVER['PHP_AUTH_USER'])) {
277 $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
278 $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
279 } elseif (isset($authorization_header)
280 && strstr(substr($authorization_header, 0, 5), 'Basic')) {
282 // Decode the HTTP_AUTHORIZATION header on php-cgi server self
283 // on fcgid server the header name is AUTHORIZATION
285 $auth_hash = base64_decode(substr($authorization_header, 6));
286 list($this->auth_user_nickname,
287 $this->auth_user_password) = explode(':', $auth_hash);
289 // Set all to null on a empty basic auth request
291 if (empty($this->auth_user_nickname)) {
292 $this->auth_user_nickname = null;
293 $this->auth_password = null;
299 * Output an authentication error message. Use XML or JSON if one
300 * of those formats is specified, otherwise output plain text
305 function showAuthError()
307 header('HTTP/1.1 401 Unauthorized');
308 $msg = 'Could not authenticate you.';
310 if ($this->format == 'xml') {
311 header('Content-Type: application/xml; charset=utf-8');
313 $this->elementStart('hash');
314 $this->element('error', null, $msg);
315 $this->element('request', null, $_SERVER['REQUEST_URI']);
316 $this->elementEnd('hash');
318 } elseif ($this->format == 'json') {
319 header('Content-Type: application/json; charset=utf-8');
320 $error_array = array('error' => $msg,
321 'request' => $_SERVER['REQUEST_URI']);
322 print(json_encode($error_array));
324 header('Content-type: text/plain');