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 Oputh 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
61 function isReadOnly($args)
66 function prepare($args)
68 parent::prepare($args);
70 $this->nickname = $this->trimmed('nickname');
71 $this->password = $this->arg('password');
72 $this->oauthTokenParam = $this->arg('oauth_token');
73 $this->mode = $this->arg('mode');
74 $this->store = new ApiStatusNetOAuthDataStore();
77 $this->app = $this->store->getAppByRequestToken($this->oauthTokenParam);
78 } catch (Exception $e) {
79 $this->clientError($e->getMessage());
86 * Handle input, produce output
88 * Switches on request method; either shows the form or handles its input.
90 * @param array $args $_REQUEST data
94 function handle($args)
96 parent::handle($args);
98 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
104 // Make sure a oauth_token parameter was provided
105 if (empty($this->oauthTokenParam)) {
106 // TRANS: Client error given when no oauth_token was passed to the OAuth API.
107 $this->clientError(_('No oauth_token parameter provided.'));
110 // Check to make sure the token exists
111 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
113 if (empty($this->reqToken)) {
114 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
115 $this->clientError(_('Invalid request token.'));
118 // Check to make sure we haven't already authorized the token
119 if ($this->reqToken->state != 0) {
120 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
121 $this->clientError(_('Request token already authorized.'));
126 // make sure there's an app associated with this token
127 if (empty($this->app)) {
128 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
129 $this->clientError(_('Invalid request token.'));
132 $name = $this->app->name;
138 function handlePost()
140 // check session token for CSRF protection.
142 $token = $this->trimmed('token');
144 if (!$token || $token != common_session_token()) {
146 // TRANS: Form validation error in API OAuth authorisation because of an invalid 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();
176 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
177 assert(!empty($this->reqToken));
179 if ($this->arg('allow')) {
180 // mark the req token as authorized
182 $this->store->authorize_token($this->oauthTokenParam);
183 } catch (Exception $e) {
184 $this->serverError($e->getMessage());
190 "API OAuth - User %d (%s) has authorized request token %s for OAuth application %d (%s).",
193 $this->reqToken->tok,
199 // XXX: Make sure we have a oauth_token_association table. The table
200 // is now in the main schema, but because it is being added with
201 // a point release, it's unlikely to be there. This code can be
202 // removed as of 1.0.
203 $this->ensureOauthTokenAssociationTable();
205 $tokenAssoc = new Oauth_token_association();
207 $tokenAssoc->profile_id = $user->id;
208 $tokenAssoc->application_id = $this->app->id;
209 $tokenAssoc->token = $this->oauthTokenParam;
210 $tokenAssoc->created = common_sql_now();
212 $result = $tokenAssoc->insert();
215 common_log_db_error($tokenAssoc, 'INSERT', __FILE__);
216 // TRANS: Server error displayed when a database action fails.
217 $this->serverError(_('Database error inserting oauth_token_association.'));
220 $callback = $this->getCallback();
222 if (!empty($callback) && $this->reqToken->verified_callback != 'oob') {
223 $targetUrl = $this->buildCallbackUrl(
226 'oauth_token' => $this->oauthTokenParam,
227 'oauth_verifier' => $this->reqToken->verifier // 1.0a
231 common_log(LOG_INFO, "Redirecting to callback: $targetUrl");
233 // Redirect the user to the provided OAuth callback
234 common_redirect($targetUrl, 303);
236 } elseif ($this->app->type == 2) {
237 // Strangely, a web application seems to want to do the OOB
238 // workflow. Because no callback was specified anywhere.
242 "API OAuth - No callback provided for OAuth web client ID %s (%s) "
243 . "during authorization step. Falling back to OOB workflow.",
250 // Otherwise, inform the user that the rt was authorized
251 $this->showAuthorized();
252 } else if ($this->arg('cancel')) {
256 "API OAuth - User %d (%s) refused to authorize request token %s for OAuth application %d (%s).",
259 $this->reqToken->tok,
266 $this->store->revoke_token($this->oauthTokenParam, 0);
267 } catch (Exception $e) {
268 $this->ServerError($e->getMessage());
271 $callback = $this->getCallback();
273 // If there's a callback available, inform the consumer the user
274 // has refused authorization
275 if (!empty($callback) && $this->reqToken->verified_callback != 'oob') {
276 $targetUrl = $this->buildCallbackUrl(
279 'oauth_problem' => 'user_refused',
283 common_log(LOG_INFO, "Redirecting to callback: $targetUrl");
285 // Redirect the user to the provided OAuth callback
286 common_redirect($targetUrl, 303);
289 // otherwise inform the user that authorization for the rt was declined
290 $this->showCanceled();
293 // TRANS: Client error given on when invalid data was passed through a form in the OAuth API.
294 $this->clientError(_('Unexpected form submission.'));
298 // XXX Remove this function when we hit 1.0
299 function ensureOauthTokenAssociationTable()
301 $schema = Schema::get();
303 $reqTokenCols = array(
304 new ColumnDef('profile_id', 'integer', null, true, 'PRI'),
305 new ColumnDef('application_id', 'integer', null, true, 'PRI'),
306 new ColumnDef('token', 'varchar', 255, true, 'PRI'),
307 new ColumnDef('created', 'datetime', null, false),
315 'on update CURRENT_TIMESTAMP'
319 $schema->ensureTable('oauth_token_association', $reqTokenCols);
323 * Show body - override to add a special CSS class for the authorize
324 * page's "desktop mode" (minimal display)
326 * Calls template methods
332 $bodyClasses = array();
334 if ($this->desktopMode()) {
335 $bodyClasses[] = 'oauth-desktop-mode';
338 if (common_current_user()) {
339 $bodyClasses[] = 'user_in';
342 $attrs = array('id' => strtolower($this->trimmed('action')));
344 if (!empty($bodyClasses)) {
345 $attrs['class'] = implode(' ', $bodyClasses);
348 $this->elementStart('body', $attrs);
350 $this->elementStart('div', array('id' => 'wrap'));
351 if (Event::handle('StartShowHeader', array($this))) {
353 Event::handle('EndShowHeader', array($this));
356 if (Event::handle('StartShowFooter', array($this))) {
358 Event::handle('EndShowFooter', array($this));
360 $this->elementEnd('div');
361 $this->showScripts();
362 $this->elementEnd('body');
365 function showForm($error=null)
367 $this->error = $error;
371 function showScripts()
373 parent::showScripts();
374 if (!common_logged_in()) {
375 $this->autofocus('nickname');
382 * @return string title of the page
386 // TRANS: Title for a page where a user can confirm/deny account access by an external application.
387 return _('An application would like to connect to your account');
391 * Shows the authorization form.
395 function showContent()
397 $this->elementStart('form', array('method' => 'post',
398 'id' => 'form_apioauthauthorize',
399 'class' => 'form_settings',
400 'action' => common_local_url('ApiOauthAuthorize')));
401 $this->elementStart('fieldset');
402 $this->element('legend', array('id' => 'apioauthauthorize_allowdeny'),
403 // TRANS: Fieldset legend.
404 _('Allow or deny access'));
406 $this->hidden('token', common_session_token());
407 $this->hidden('mode', $this->mode);
408 $this->hidden('oauth_token', $this->oauthTokenParam);
409 $this->hidden('oauth_callback', $this->callback);
411 $this->elementStart('ul', 'form_data');
412 $this->elementStart('li');
413 $this->elementStart('p');
414 if (!empty($this->app->icon) && $this->app->name != 'anonymous') {
415 $this->element('img', array('src' => $this->app->icon));
418 $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
419 'access and update' : 'access';
421 if ($this->app->name == 'anonymous') {
422 // Special message for the anonymous app and consumer.
423 // TRANS: User notification of external application requesting account access.
424 // TRANS: %3$s is the access type requested (read-write or read-only), %4$s is the StatusNet sitename.
425 $msg = _('An application would like the ability ' .
426 'to <strong>%3$s</strong> your %4$s account data. ' .
427 'You should only give access to your %4$s account ' .
428 'to third parties you trust.');
430 // TRANS: User notification of external application requesting account access.
431 // TRANS: %1$s is the application name requesting access, %2$s is the organisation behind the application,
432 // TRANS: %3$s is the access type requested, %4$s is the StatusNet sitename.
433 $msg = _('The application <strong>%1$s</strong> by ' .
434 '<strong>%2$s</strong> would like the ability ' .
435 'to <strong>%3$s</strong> your %4$s account data. ' .
436 'You should only give access to your %4$s account ' .
437 'to third parties you trust.');
440 $this->raw(sprintf($msg,
442 $this->app->organization,
444 common_config('site', 'name')));
445 $this->elementEnd('p');
446 $this->elementEnd('li');
447 $this->elementEnd('ul');
451 if (!common_logged_in()) {
452 if (Event::handle('StartOAuthLoginForm', array($this, &$button))) {
453 $this->elementStart('fieldset');
454 // TRANS: Fieldset legend.
455 $this->element('legend', null, _m('LEGEND','Account'));
456 $this->elementStart('ul', 'form_data');
457 $this->elementStart('li');
458 // TRANS: Field label on OAuth API authorisation form.
459 $this->input('nickname', _('Nickname'));
460 $this->elementEnd('li');
461 $this->elementStart('li');
462 // TRANS: Field label on OAuth API authorisation form.
463 $this->password('password', _('Password'));
464 $this->elementEnd('li');
465 $this->elementEnd('ul');
467 $this->elementEnd('fieldset');
469 Event::handle('EndOAuthLoginForm', array($this, &$button));
472 $this->element('input', array('id' => 'cancel_submit',
473 'class' => 'submit submit form_action-primary',
476 // TRANS: Button text that when clicked will cancel the process of allowing access to an account
477 // TRANS: by an external application.
478 'value' => _m('BUTTON','Cancel')));
480 $this->element('input', array('id' => 'allow_submit',
481 'class' => 'submit submit form_action-secondary',
484 // TRANS: Button text that when clicked will allow access to an account by an external application.
485 'value' => $button ? $button : _m('BUTTON','Allow')));
487 $this->elementEnd('fieldset');
488 $this->elementEnd('form');
492 * Instructions for using the form
494 * For "remembered" logins, we make the user re-login when they
495 * try to change settings. Different instructions for this case.
499 function getInstructions()
501 // TRANS: Form instructions.
502 return _('Authorize access to your account information.');
508 * Shows different login/register actions.
512 function showLocalNav()
518 * Checks to see if a the "mode" parameter is present in the request
519 * and set to "desktop". If it is, the page is meant to be displayed in
520 * a small frame of another application, and we should suppress the
521 * header, aside, and footer.
523 function desktopMode()
525 if (isset($this->mode) && $this->mode == 'desktop') {
533 * Override - suppress output in "desktop" mode
535 function showHeader()
537 if ($this->desktopMode() == false) {
538 parent::showHeader();
543 * Override - suppress output in "desktop" mode
547 if ($this->desktopMode() == false) {
553 * Override - suppress output in "desktop" mode
555 function showFooter()
557 if ($this->desktopMode() == false) {
558 parent::showFooter();
567 function showSiteNotice()
575 * Show the form for posting a new notice
579 function showNoticeForm()
585 * Show a nice message confirming the authorization
586 * operation was canceled.
590 function showCanceled()
592 $info = new InfoAction(
593 // TRANS: Header for user notification after revoking OAuth access to an application.
594 _('Authorization canceled.'),
596 // TRANS: User notification after revoking OAuth access to an application.
597 // TRANS: %s is an OAuth token.
598 _('The request token %s has been revoked.'),
599 $this->oauthTokenParam
607 * Show a nice message that the authorization was successful.
608 * If the operation is out-of-band, show a pin.
612 function showAuthorized()
617 if ($this->app->name == 'anonymous') {
620 // TRANS: Title of the page notifying the user that an anonymous client application was successfully authorized to access the user's account with OAuth.
621 _('You have successfully authorized the application');
624 // TRANS: Message notifying the user that an anonymous client application was successfully authorized to access the user's account with OAuth.
625 _('Please return to the application and enter the following security code to complete the process.');
630 // TRANS: Title of the page notifying the user that the client application was successfully authorized to access the user's account with OAuth.
631 // TRANS: %s is the authorised application name.
632 _('You have successfully authorized %s'),
637 // TRANS: Message notifying the user that the client application was successfully authorized to access the user's account with OAuth.
638 // TRANS: %s is the authorised application name.
639 _('Please return to %s and enter the following security code to complete the process.'),
645 if ($this->reqToken->verified_callback == 'oob') {
646 $pin = new ApiOauthPinAction(
649 $this->reqToken->verifier,
654 // NOTE: This would only happen if an application registered as
655 // a web application but sent in 'oob' for the oauth_callback
656 // parameter. Usually web apps will send in a callback and
657 // not use the pin-based workflow.
659 $info = new InfoAction(
662 $this->oauthTokenParam,
663 $this->reqToken->verifier
671 * Figure out what the callback should be
673 function getCallback()
677 // Return the verified callback if we have one
678 if ($this->reqToken->verified_callback != 'oob') {
680 $callback = $this->reqToken->verified_callback;
682 // Otherwise return the callback that was provided when
683 // registering the app
684 if (empty($callback)) {
687 "No verified callback found for request token, using application callback: "
688 . $this->app->callback_url,
692 $callback = $this->app->callback_url;
700 * Properly format the callback URL and parameters so it's
701 * suitable for a redirect in the OAuth dance
703 * @param string $url the URL
704 * @param array $params an array of parameters
706 * @return string $url a URL to use for redirecting to
708 function buildCallbackUrl($url, $params)
710 foreach ($params as $k => $v) {
711 $url = $this->appendQueryVar(
713 OAuthUtil::urlencode_rfc3986($k),
714 OAuthUtil::urlencode_rfc3986($v)
722 * Append a new query parameter after any existing query
725 * @param string $url the URL
726 * @prarm string $k the parameter name
727 * @param string $v value of the paramter
729 * @return string $url the new URL with added parameter
731 function appendQueryVar($url, $k, $v) {
732 $url = preg_replace('/(.*)(\?|&)' . $k . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
733 $url = substr($url, 0, -1);
734 if (strpos($url, '?') === false) {
735 return ($url . '?' . $k . '=' . $v);
737 return ($url . '&' . $k . '=' . $v);