3 * StatusNet, the distributed open-source microblogging tool
5 * Authorize an OAuth request token
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 Zach Copley <zach@status.net>
25 * @copyright 2010 StatusNet, Inc.
26 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27 * @link http://status.net/
30 if (!defined('STATUSNET')) {
34 require_once INSTALLDIR . '/lib/apioauth.php';
35 require_once INSTALLDIR . '/lib/info.php';
38 * Authorize an OAuth request token
42 * @author Zach Copley <zach@status.net>
43 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
44 * @link http://status.net/
46 class ApiOauthAuthorizeAction extends Action
57 * Is this a read-only action?
59 * @return boolean false
62 function isReadOnly($args)
67 function prepare($args)
69 parent::prepare($args);
71 $this->nickname = $this->trimmed('nickname');
72 $this->password = $this->arg('password');
73 $this->oauthTokenParam = $this->arg('oauth_token');
74 $this->callback = $this->arg('oauth_callback');
75 $this->store = new ApiStatusNetOAuthDataStore();
78 $this->app = $this->store->getAppByRequestToken($this->oauthTokenParam);
79 } catch (Exception $e) {
80 $this->clientError($e->getMessage());
87 * Handle input, produce output
89 * Switches on request method; either shows the form or handles its input.
91 * @param array $args $_REQUEST data
95 function handle($args)
97 parent::handle($args);
99 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
105 // Make sure a oauth_token parameter was provided
106 if (empty($this->oauthTokenParam)) {
107 // TRANS: Client error given when no oauth_token was passed to the OAuth API.
108 $this->clientError(_('No oauth_token parameter provided.'));
111 // Check to make sure the token exists
112 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
114 if (empty($this->reqToken)) {
115 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
116 $this->clientError(_('Invalid request token.'));
119 // Check to make sure we haven't already authorized the token
120 if ($this->reqToken->state != 0) {
121 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
122 $this->clientError(_('Invalid request token.'));
127 // make sure there's an app associated with this token
128 if (empty($this->app)) {
129 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
130 $this->clientError(_('Invalid request token.'));
133 $name = $this->app->name;
139 function handlePost()
141 // check session token for CSRF protection.
143 $token = $this->trimmed('token');
145 if (!$token || $token != common_session_token()) {
147 _('There was a problem with your session token. Try again, please.'));
155 if (!common_logged_in()) {
157 // XXX Force credentials check?
159 // @fixme this should probably use a unified login form handler
161 if (Event::handle('StartOAuthLoginCheck', array($this, &$user))) {
162 $user = common_check_user($this->nickname, $this->password);
164 Event::handle('EndOAuthLoginCheck', array($this, &$user));
167 // TRANS: Form validation error given when an invalid username and/or password was passed to the OAuth API.
168 $this->showForm(_("Invalid nickname / password!"));
172 $user = common_current_user();
175 if ($this->arg('allow')) {
178 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
180 // mark the req token as authorized
182 $this->store->authorize_token($this->oauthTokenParam);
183 } catch (Exception $e) {
184 $this->serverError($e->getMessage());
187 // XXX: Make sure we have a oauth_token_association table. The table
188 // is now in the main schema, but because it is being added with
189 // a point release, it's unlikely to be there. This code can be
190 // removed as of 1.0.
191 $this->ensureOauthTokenAssociationTable();
193 $tokenAssoc = new Oauth_token_association();
195 $tokenAssoc->profile_id = $user->id;
196 $tokenAssoc->application_id = $this->app->id;
197 $tokenAssoc->token = $this->oauthTokenParam;
198 $tokenAssoc->created = common_sql_now();
200 $result = $tokenAssoc->insert();
203 common_log_db_error($tokenAssoc, 'INSERT', __FILE__);
204 // TRANS: Server error displayed when a database action fails.
205 $this->serverError(_('Database error inserting oauth_token_association.'));
208 // If we have a callback redirect and provide the token
210 // Note: A callback specified in the app setup overrides whatever
211 // is passed in with the request.
213 if (!empty($this->app->callback_url)) {
214 $this->callback = $this->app->callback_url;
217 if (!empty($this->callback)) {
218 $targetUrl = $this->getCallback(
221 'oauth_token' => $this->oauthTokenParam,
222 'oauth_verifier' => $this->reqToken->verifier // 1.0a
226 // Redirect the user to the provided OAuth callback
227 common_redirect($targetUrl, 303);
228 } elseif ($this->app->type == 2) {
229 // Strangely, a web application seems to want to do the OOB
230 // workflow. Because no callback was specified anywhere.
234 "API OAuth - No callback provided for OAuth web client ID %s (%s) "
235 . "during authorization step. Falling back to OOB workflow.",
245 "The request token '%s' for OAuth application %s (%s) has been authorized.",
246 $this->oauthTokenParam,
252 // Otherwise, inform the user that the rt was authorized
253 $this->showAuthorized();
254 } else if ($this->arg('cancel')) {
256 $this->store->revoke_token($this->oauthTokenParam, 0);
257 $this->showCanceled();
258 } catch (Exception $e) {
259 $this->ServerError($e->getMessage());
262 // TRANS: Client error given on when invalid data was passed through a form in the OAuth API.
263 $this->clientError(_('Unexpected form submission.'));
267 // XXX Remove this function when we hit 1.0
268 function ensureOauthTokenAssociationTable()
270 $schema = Schema::get();
272 $reqTokenCols = array(
273 new ColumnDef('profile_id', 'integer', null, true, 'PRI'),
274 new ColumnDef('application_id', 'integer', null, true, 'PRI'),
275 new ColumnDef('token', 'varchar', 255, true, 'PRI'),
276 new ColumnDef('created', 'datetime', null, false),
284 'on update CURRENT_TIMESTAMP'
288 $schema->ensureTable('oauth_token_association', $reqTokenCols);
291 function showForm($error=null)
293 $this->error = $error;
297 function showScripts()
299 parent::showScripts();
300 if (!common_logged_in()) {
301 $this->autofocus('nickname');
308 * @return string title of the page
312 // TRANS: Title for a page where a user can confirm/deny account access by an external application.
313 return _('An application would like to connect to your account');
317 * Shows the authorization form.
321 function showContent()
323 $this->elementStart('form', array('method' => 'post',
324 'id' => 'form_apioauthauthorize',
325 'class' => 'form_settings',
326 'action' => common_local_url('ApiOauthAuthorize')));
327 $this->elementStart('fieldset');
328 $this->element('legend', array('id' => 'apioauthauthorize_allowdeny'),
329 // TRANS: Fieldset legend.
330 _('Allow or deny access'));
332 $this->hidden('token', common_session_token());
333 $this->hidden('oauth_token', $this->oauthTokenParam);
334 $this->hidden('oauth_callback', $this->callback);
336 $this->elementStart('ul', 'form_data');
337 $this->elementStart('li');
338 $this->elementStart('p');
339 if (!empty($this->app->icon)) {
340 $this->element('img', array('src' => $this->app->icon));
343 $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
344 'access and update' : 'access';
346 // TRANS: User notification of external application requesting account access.
347 // TRANS: %1$s is the application name requesting access, %2$s is the organisation behind the application,
348 // TRANS: %3$s is the access type requested, %4$s is the StatusNet sitename.
349 $msg = _('The application <strong>%1$s</strong> by ' .
350 '<strong>%2$s</strong> would like the ability ' .
351 'to <strong>%3$s</strong> your %4$s account data. ' .
352 'You should only give access to your %4$s account ' .
353 'to third parties you trust.');
355 $this->raw(sprintf($msg,
357 $this->app->organization,
359 common_config('site', 'name')));
360 $this->elementEnd('p');
361 $this->elementEnd('li');
362 $this->elementEnd('ul');
366 if (!common_logged_in()) {
367 if (Event::handle('StartOAuthLoginForm', array($this, &$button))) {
368 $this->elementStart('fieldset');
369 // TRANS: Fieldset legend.
370 $this->element('legend', null, _m('LEGEND','Account'));
371 $this->elementStart('ul', 'form_data');
372 $this->elementStart('li');
373 // TRANS: Field label on OAuth API authorisation form.
374 $this->input('nickname', _('Nickname'));
375 $this->elementEnd('li');
376 $this->elementStart('li');
377 // TRANS: Field label on OAuth API authorisation form.
378 $this->password('password', _('Password'));
379 $this->elementEnd('li');
380 $this->elementEnd('ul');
382 $this->elementEnd('fieldset');
384 Event::handle('EndOAuthLoginForm', array($this, &$button));
387 $this->element('input', array('id' => 'cancel_submit',
388 'class' => 'submit submit form_action-primary',
391 // TRANS: Button text that when clicked will cancel the process of allowing access to an account
392 // TRANS: by an external application.
393 'value' => _m('BUTTON','Cancel')));
395 $this->element('input', array('id' => 'allow_submit',
396 'class' => 'submit submit form_action-secondary',
399 // TRANS: Button text that when clicked will allow access to an account by an external application.
400 'value' => $button ? $button : _m('BUTTON','Allow')));
402 $this->elementEnd('fieldset');
403 $this->elementEnd('form');
407 * Instructions for using the form
409 * For "remembered" logins, we make the user re-login when they
410 * try to change settings. Different instructions for this case.
414 function getInstructions()
416 // TRANS: Form instructions.
417 return _('Authorize access to your account information.');
423 * Shows different login/register actions.
427 function showLocalNav()
437 function showSiteNotice()
445 * Show the form for posting a new notice
449 function showNoticeForm()
455 * Show a nice message confirming the authorization
456 * operation was canceled.
460 function showCanceled()
462 $info = new InfoAction(
463 // TRANS: Header for user notification after revoking OAuth access to an application.
464 _('Authorization canceled.'),
466 // TRANS: User notification after revoking OAuth access to an application.
467 // TRANS: %s is an OAuth token.
468 _('The request token %s has been revoked.'),
469 $this->oauthTokenParm
477 * Show a nice message that the authorization was successful.
478 * If the operation is out-of-band, show a pin.
482 function showAuthorized()
485 // TRANS: Header of user notification after authorising an application access to a profile.
486 // TRANS: %s is the authorised application name.
487 _("You have successfully authorized %s."),
492 // TRANS: Uer notification after authorising an application access to a profile.
493 // TRANS: %s is the authorised application name.
494 _('Please return to %s and enter the following security code to complete the process.'),
498 if ($this->reqToken->verified_callback == 'oob') {
499 $pin = new ApiOauthPinAction($title, $msg, $this->reqToken->verifier);
503 // NOTE: This would only happen if an application registered as
504 // a web application but sent in 'oob' for the oauth_callback
505 // parameter. Usually web apps will send in a callback and
506 // not use the pin-based workflow.
508 $info = new InfoAction(
511 $this->oauthTokenParam,
512 $this->reqToken->verifier
520 * Properly format the callback URL and parameters so it's
521 * suitable for a redirect in the OAuth dance
523 * @param string $url the URL
524 * @param array $params an array of parameters
526 * @return string $url a URL to use for redirecting to
528 function getCallback($url, $params)
530 foreach ($params as $k => $v) {
531 $url = $this->appendQueryVar(
533 OAuthUtil::urlencode_rfc3986($k),
534 OAuthUtil::urlencode_rfc3986($v)
542 * Append a new query parameter after any existing query
545 * @param string $url the URL
546 * @prarm string $k the parameter name
547 * @param string $v value of the paramter
549 * @return string $url the new URL with added parameter
551 function appendQueryVar($url, $k, $v) {
552 $url = preg_replace('/(.*)(\?|&)' . $k . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
553 $url = substr($url, 0, -1);
554 if (strpos($url, '?') === false) {
555 return ($url . '?' . $k . '=' . $v);
557 return ($url . '&' . $k . '=' . $v);