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-2011 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')) {
35 * Authorize an OAuth request token
39 * @author Zach Copley <zach@status.net>
40 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
41 * @link http://status.net/
43 class ApiOAuthAuthorizeAction extends ApiOAuthAction
54 * Is this a read-only action?
56 * @return boolean false
58 function isReadOnly($args)
63 function prepare($args)
65 parent::prepare($args);
67 $this->nickname = $this->trimmed('nickname');
68 $this->password = $this->arg('password');
69 $this->oauthTokenParam = $this->arg('oauth_token');
70 $this->mode = $this->arg('mode');
71 $this->store = new ApiGNUsocialOAuthDataStore();
74 $this->app = $this->store->getAppByRequestToken($this->oauthTokenParam);
75 } catch (Exception $e) {
76 $this->clientError($e->getMessage());
83 * Handle input, produce output
85 * Switches on request method; either shows the form or handles its input.
87 * @param array $args $_REQUEST data
91 function handle($args)
93 parent::handle($args);
95 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
101 // Make sure a oauth_token parameter was provided
102 if (empty($this->oauthTokenParam)) {
103 // TRANS: Client error given when no oauth_token was passed to the OAuth API.
104 $this->clientError(_('No oauth_token parameter provided.'));
107 // Check to make sure the token exists
108 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
110 if (empty($this->reqToken)) {
111 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
112 $this->clientError(_('Invalid request token.'));
115 // Check to make sure we haven't already authorized the token
116 if ($this->reqToken->state != 0) {
117 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
118 $this->clientError(_('Request token already authorized.'));
123 // make sure there's an app associated with this token
124 if (empty($this->app)) {
125 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
126 $this->clientError(_('Invalid request token.'));
129 $name = $this->app->name;
135 function handlePost()
137 // check session token for CSRF protection.
139 $token = $this->trimmed('token');
141 if (!$token || $token != common_session_token()) {
143 // TRANS: Form validation error in API OAuth authorisation because of an invalid session token.
144 _('There was a problem with your session token. Try again, please.'));
152 if (!common_logged_in()) {
154 // XXX Force credentials check?
156 // @fixme this should probably use a unified login form handler
158 if (Event::handle('StartOAuthLoginCheck', array($this, &$user))) {
159 $user = common_check_user($this->nickname, $this->password);
161 Event::handle('EndOAuthLoginCheck', array($this, &$user));
164 // TRANS: Form validation error given when an invalid username and/or password was passed to the OAuth API.
165 $this->showForm(_("Invalid nickname / password!"));
169 $user = common_current_user();
173 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
174 assert(!empty($this->reqToken));
176 if ($this->arg('allow')) {
177 // mark the req token as authorized
179 $this->store->authorize_token($this->oauthTokenParam);
180 } catch (Exception $e) {
181 $this->serverError($e->getMessage());
187 "API OAuth - User %d (%s) has authorized request token %s for OAuth application %d (%s).",
190 $this->reqToken->tok,
196 $tokenAssoc = new Oauth_token_association();
198 $tokenAssoc->profile_id = $user->id;
199 $tokenAssoc->application_id = $this->app->id;
200 $tokenAssoc->token = $this->oauthTokenParam;
201 $tokenAssoc->created = common_sql_now();
203 $result = $tokenAssoc->insert();
206 common_log_db_error($tokenAssoc, 'INSERT', __FILE__);
207 // TRANS: Server error displayed when a database action fails.
208 $this->serverError(_('Database error inserting oauth_token_association.'));
211 $callback = $this->getCallback();
213 if (!empty($callback) && $this->reqToken->verified_callback != 'oob') {
214 $targetUrl = $this->buildCallbackUrl(
217 'oauth_token' => $this->oauthTokenParam,
218 'oauth_verifier' => $this->reqToken->verifier // 1.0a
222 common_log(LOG_INFO, "Redirecting to callback: $targetUrl");
224 // Redirect the user to the provided OAuth callback
225 common_redirect($targetUrl, 303);
227 } elseif ($this->app->type == 2) {
228 // Strangely, a web application seems to want to do the OOB
229 // workflow. Because no callback was specified anywhere.
233 "API OAuth - No callback provided for OAuth web client ID %s (%s) "
234 . "during authorization step. Falling back to OOB workflow.",
241 // Otherwise, inform the user that the rt was authorized
242 $this->showAuthorized();
243 } else if ($this->arg('cancel')) {
247 "API OAuth - User %d (%s) refused to authorize request token %s for OAuth application %d (%s).",
250 $this->reqToken->tok,
257 $this->store->revoke_token($this->oauthTokenParam, 0);
258 } catch (Exception $e) {
259 $this->ServerError($e->getMessage());
262 $callback = $this->getCallback();
264 // If there's a callback available, inform the consumer the user
265 // has refused authorization
266 if (!empty($callback) && $this->reqToken->verified_callback != 'oob') {
267 $targetUrl = $this->buildCallbackUrl(
270 'oauth_problem' => 'user_refused',
274 common_log(LOG_INFO, "Redirecting to callback: $targetUrl");
276 // Redirect the user to the provided OAuth callback
277 common_redirect($targetUrl, 303);
280 // otherwise inform the user that authorization for the rt was declined
281 $this->showCanceled();
284 // TRANS: Client error given on when invalid data was passed through a form in the OAuth API.
285 $this->clientError(_('Unexpected form submission.'));
290 * Show body - override to add a special CSS class for the authorize
291 * page's "desktop mode" (minimal display)
293 * Calls template methods
299 $bodyClasses = array();
301 if ($this->desktopMode()) {
302 $bodyClasses[] = 'oauth-desktop-mode';
305 if (common_current_user()) {
306 $bodyClasses[] = 'user_in';
309 $attrs = array('id' => strtolower($this->trimmed('action')));
311 if (!empty($bodyClasses)) {
312 $attrs['class'] = implode(' ', $bodyClasses);
315 $this->elementStart('body', $attrs);
317 $this->elementStart('div', array('id' => 'wrap'));
318 if (Event::handle('StartShowHeader', array($this))) {
320 Event::handle('EndShowHeader', array($this));
323 if (Event::handle('StartShowFooter', array($this))) {
325 Event::handle('EndShowFooter', array($this));
327 $this->elementEnd('div');
328 $this->showScripts();
329 $this->elementEnd('body');
332 function showForm($error=null)
334 $this->error = $error;
338 function showScripts()
340 parent::showScripts();
341 if (!common_logged_in()) {
342 $this->autofocus('nickname');
349 * @return string title of the page
353 // TRANS: Title for a page where a user can confirm/deny account access by an external application.
354 return _('An application would like to connect to your account');
358 * Shows the authorization form.
362 function showContent()
364 $this->elementStart('form', array('method' => 'post',
365 'id' => 'form_apioauthauthorize',
366 'class' => 'form_settings',
367 'action' => common_local_url('ApiOAuthAuthorize')));
368 $this->elementStart('fieldset');
369 $this->element('legend', array('id' => 'apioauthauthorize_allowdeny'),
370 // TRANS: Fieldset legend.
371 _('Allow or deny access'));
373 $this->hidden('token', common_session_token());
374 $this->hidden('mode', $this->mode);
375 $this->hidden('oauth_token', $this->oauthTokenParam);
376 $this->hidden('oauth_callback', $this->callback);
378 $this->elementStart('ul', 'form_data');
379 $this->elementStart('li');
380 $this->elementStart('p');
381 if (!empty($this->app->icon) && $this->app->name != 'anonymous') {
382 $this->element('img', array('src' => $this->app->icon));
385 $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
386 'access and update' : 'access';
388 if ($this->app->name == 'anonymous') {
389 // Special message for the anonymous app and consumer.
390 // TRANS: User notification of external application requesting account access.
391 // TRANS: %3$s is the access type requested (read-write or read-only), %4$s is the StatusNet sitename.
392 $msg = _('An application would like the ability ' .
393 'to <strong>%3$s</strong> your %4$s account data. ' .
394 'You should only give access to your %4$s account ' .
395 'to third parties you trust.');
397 // TRANS: User notification of external application requesting account access.
398 // TRANS: %1$s is the application name requesting access, %2$s is the organisation behind the application,
399 // TRANS: %3$s is the access type requested, %4$s is the StatusNet sitename.
400 $msg = _('The application <strong>%1$s</strong> by ' .
401 '<strong>%2$s</strong> would like the ability ' .
402 'to <strong>%3$s</strong> your %4$s account data. ' .
403 'You should only give access to your %4$s account ' .
404 'to third parties you trust.');
407 $this->raw(sprintf($msg,
409 $this->app->organization,
411 common_config('site', 'name')));
412 $this->elementEnd('p');
413 $this->elementEnd('li');
414 $this->elementEnd('ul');
418 if (!common_logged_in()) {
419 if (Event::handle('StartOAuthLoginForm', array($this, &$button))) {
420 $this->elementStart('fieldset');
421 // TRANS: Fieldset legend.
422 $this->element('legend', null, _m('LEGEND','Account'));
423 $this->elementStart('ul', 'form_data');
424 $this->elementStart('li');
425 // TRANS: Field label on OAuth API authorisation form.
426 $this->input('nickname', _('Nickname'));
427 $this->elementEnd('li');
428 $this->elementStart('li');
429 // TRANS: Field label on OAuth API authorisation form.
430 $this->password('password', _('Password'));
431 $this->elementEnd('li');
432 $this->elementEnd('ul');
434 $this->elementEnd('fieldset');
436 Event::handle('EndOAuthLoginForm', array($this, &$button));
439 $this->element('input', array('id' => 'cancel_submit',
440 'class' => 'submit submit form_action-primary',
443 // TRANS: Button text that when clicked will cancel the process of allowing access to an account
444 // TRANS: by an external application.
445 'value' => _m('BUTTON','Cancel')));
447 $this->element('input', array('id' => 'allow_submit',
448 'class' => 'submit submit form_action-secondary',
451 // TRANS: Button text that when clicked will allow access to an account by an external application.
452 'value' => $button ? $button : _m('BUTTON','Allow')));
454 $this->elementEnd('fieldset');
455 $this->elementEnd('form');
459 * Instructions for using the form
461 * For "remembered" logins, we make the user re-login when they
462 * try to change settings. Different instructions for this case.
466 function getInstructions()
468 // TRANS: Form instructions.
469 return _('Authorize access to your account information.');
475 * Shows different login/register actions.
479 function showLocalNav()
485 * Checks to see if a the "mode" parameter is present in the request
486 * and set to "desktop". If it is, the page is meant to be displayed in
487 * a small frame of another application, and we should suppress the
488 * header, aside, and footer.
490 function desktopMode()
492 if (isset($this->mode) && $this->mode == 'desktop') {
500 * Override - suppress output in "desktop" mode
502 function showHeader()
504 if ($this->desktopMode() == false) {
505 parent::showHeader();
510 * Override - suppress output in "desktop" mode
514 if ($this->desktopMode() == false) {
520 * Override - suppress output in "desktop" mode
522 function showFooter()
524 if ($this->desktopMode() == false) {
525 parent::showFooter();
534 function showSiteNotice()
542 * Show the form for posting a new notice
546 function showNoticeForm()
552 * Show a nice message confirming the authorization
553 * operation was canceled.
557 function showCanceled()
559 $info = new InfoAction(
560 // TRANS: Header for user notification after revoking OAuth access to an application.
561 _('Authorization canceled.'),
563 // TRANS: User notification after revoking OAuth access to an application.
564 // TRANS: %s is an OAuth token.
565 _('The request token %s has been revoked.'),
566 $this->oauthTokenParam
574 * Show a nice message that the authorization was successful.
575 * If the operation is out-of-band, show a pin.
579 function showAuthorized()
584 if ($this->app->name == 'anonymous') {
587 // TRANS: Title of the page notifying the user that an anonymous client application was successfully authorized to access the user's account with OAuth.
588 _('You have successfully authorized the application');
591 // TRANS: Message notifying the user that an anonymous client application was successfully authorized to access the user's account with OAuth.
592 _('Please return to the application and enter the following security code to complete the process.');
597 // TRANS: Title of the page notifying the user that the client application was successfully authorized to access the user's account with OAuth.
598 // TRANS: %s is the authorised application name.
599 _('You have successfully authorized %s'),
604 // TRANS: Message notifying the user that the client application was successfully authorized to access the user's account with OAuth.
605 // TRANS: %s is the authorised application name.
606 _('Please return to %s and enter the following security code to complete the process.'),
612 if ($this->reqToken->verified_callback == 'oob') {
613 $pin = new ApiOAuthPinAction(
616 $this->reqToken->verifier,
621 // NOTE: This would only happen if an application registered as
622 // a web application but sent in 'oob' for the oauth_callback
623 // parameter. Usually web apps will send in a callback and
624 // not use the pin-based workflow.
626 $info = new InfoAction(
629 $this->oauthTokenParam,
630 $this->reqToken->verifier
638 * Figure out what the callback should be
640 function getCallback()
644 // Return the verified callback if we have one
645 if ($this->reqToken->verified_callback != 'oob') {
647 $callback = $this->reqToken->verified_callback;
649 // Otherwise return the callback that was provided when
650 // registering the app
651 if (empty($callback)) {
654 "No verified callback found for request token, using application callback: "
655 . $this->app->callback_url,
659 $callback = $this->app->callback_url;
667 * Properly format the callback URL and parameters so it's
668 * suitable for a redirect in the OAuth dance
670 * @param string $url the URL
671 * @param array $params an array of parameters
673 * @return string $url a URL to use for redirecting to
675 function buildCallbackUrl($url, $params)
677 foreach ($params as $k => $v) {
678 $url = $this->appendQueryVar(
680 OAuthUtil::urlencode_rfc3986($k),
681 OAuthUtil::urlencode_rfc3986($v)
689 * Append a new query parameter after any existing query
692 * @param string $url the URL
693 * @prarm string $k the parameter name
694 * @param string $v value of the paramter
696 * @return string $url the new URL with added parameter
698 function appendQueryVar($url, $k, $v) {
699 $url = preg_replace('/(.*)(\?|&)' . $k . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
700 $url = substr($url, 0, -1);
701 if (strpos($url, '?') === false) {
702 return ($url . '?' . $k . '=' . $v);
704 return ($url . '&' . $k . '=' . $v);