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 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/apioauthstore.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
57 var $oauth_access_type;
60 * Take arguments for running, and output basic auth header if needed
62 * @param array $args $_REQUEST args
64 * @return boolean success flag
68 function prepare($args)
70 parent::prepare($args);
72 if ($this->requiresAuth()) {
74 $this->consumer_key = $this->arg('oauth_consumer_key');
75 $this->access_token = $this->arg('oauth_token');
77 if (!empty($this->access_token)) {
78 $this->checkOAuthRequest();
80 $this->checkBasicAuthUser();
87 function checkOAuthRequest()
89 common_debug("We have an OAuth request.");
91 $datastore = new ApiStatusNetOAuthDataStore();
92 $server = new OAuthServer($datastore);
93 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
95 $server->add_signature_method($hmac_method);
97 $this->cleanRequest();
101 $req = OAuthRequest::from_request();
102 $server->verify_request($req);
104 common_debug("Good OAuth request!");
106 $app = Oauth_application::getByConsumerKey($this->consumer_key);
110 // this should really not happen
112 "Couldn't find the OAuth app for consumer key: $this->consumer_key");
114 throw new OAuthException('No application for that consumer key.');
117 $appUser = Oauth_application_user::staticGet('token',
118 $this->access_token);
120 // XXX: check that app->id and appUser->application_id and consumer all
123 if (!empty($appUser)) {
125 // read or read-write
126 $this->oauth_access_type = $appUser->access_type;
128 // If access_type == 0 we have either a request token
129 // or a bad / revoked access token
131 if ($this->oauth_access_type != 0) {
133 $this->auth_user = User::staticGet('id', $appUser->profile_id);
135 $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
136 "application '%s' (id: %d).";
138 common_log(LOG_INFO, sprintf($msg,
139 $this->auth_user->nickname,
140 $this->auth_user->id,
145 throw new OAuthException('Bad access token.');
149 // also should not happen
150 throw new OAuthException('No user for that token.');
153 } catch (OAuthException $e) {
154 common_log(LOG_WARN, 'API OAuthException - ' . $e->getMessage());
155 common_debug(var_export($req, true));
156 $this->showOAuthError($e->getMessage());
161 function showOAuthError($msg)
163 header('HTTP/1.1 401 Unauthorized');
164 header('Content-Type: text/html; charset=utf-8');
168 function cleanRequest()
170 // kill evil effects of magical slashing
172 if(get_magic_quotes_gpc() == 1) {
173 $_POST = array_map('stripslashes', $_POST);
174 $_GET = array_map('stripslashes', $_GET);
177 // strip out the p param added in index.php
179 // XXX: should we strip anything else? Or alternatively
180 // only allow a known list of params?
187 * Does this API resource require authentication?
189 * @return boolean true
192 function requiresAuth()
198 * Check for a user specified via HTTP basic auth. If there isn't
199 * one, try to get one by outputting the basic auth header.
201 * @return boolean true or false
204 function checkBasicAuthUser()
206 $this->basicAuthProcessHeader();
208 $realm = common_config('site', 'name') . ' API';
210 if (!isset($this->auth_user)) {
211 header('WWW-Authenticate: Basic realm="' . $realm . '"');
213 // show error if the user clicks 'cancel'
215 $this->showBasicAuthError();
219 $nickname = $this->auth_user;
220 $password = $this->auth_pw;
221 $user = common_check_user($nickname, $password);
222 if (Event::handle('StartSetApiUser', array(&$user))) {
223 $this->auth_user = $user;
224 Event::handle('EndSetApiUser', array($user));
227 if (empty($this->auth_user)) {
229 // basic authentication failed
231 list($proxy, $ip) = common_client_ip();
234 'Failed API auth attempt, nickname = ' .
235 "$nickname, proxy = $proxy, ip = $ip."
237 $this->showBasicAuthError();
245 * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
246 * param to support basic auth when PHP is running in CGI mode.
251 function basicAuthProcessHeader()
253 if (isset($_SERVER['AUTHORIZATION'])
254 || isset($_SERVER['HTTP_AUTHORIZATION'])
256 $authorization_header = isset($_SERVER['HTTP_AUTHORIZATION'])
257 ? $_SERVER['HTTP_AUTHORIZATION'] : $_SERVER['AUTHORIZATION'];
260 if (isset($_SERVER['PHP_AUTH_USER'])) {
261 $this->auth_user = $_SERVER['PHP_AUTH_USER'];
262 $this->auth_pw = $_SERVER['PHP_AUTH_PW'];
263 } elseif (isset($authorization_header)
264 && strstr(substr($authorization_header, 0, 5), 'Basic')) {
266 // decode the HTTP_AUTHORIZATION header on php-cgi server self
267 // on fcgid server the header name is AUTHORIZATION
269 $auth_hash = base64_decode(substr($authorization_header, 6));
270 list($this->auth_user, $this->auth_pw) = explode(':', $auth_hash);
272 // set all to null on a empty basic auth request
274 if ($this->auth_user == "") {
275 $this->auth_user = null;
276 $this->auth_pw = null;
279 $this->auth_user = null;
280 $this->auth_pw = null;
285 * Output an authentication error message. Use XML or JSON if one
286 * of those formats is specified, otherwise output plain text
291 function showBasicAuthError()
293 header('HTTP/1.1 401 Unauthorized');
294 $msg = 'Could not authenticate you.';
296 if ($this->format == 'xml') {
297 header('Content-Type: application/xml; charset=utf-8');
299 $this->elementStart('hash');
300 $this->element('error', null, $msg);
301 $this->element('request', null, $_SERVER['REQUEST_URI']);
302 $this->elementEnd('hash');
304 } elseif ($this->format == 'json') {
305 header('Content-Type: application/json; charset=utf-8');
306 $error_array = array('error' => $msg,
307 'request' => $_SERVER['REQUEST_URI']);
308 print(json_encode($error_array));
310 header('Content-type: text/plain');