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
96 function handle($args)
98 parent::handle($args);
100 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
106 // Make sure a oauth_token parameter was provided
107 if (empty($this->oauthTokenParam)) {
108 // TRANS: Client error given when no oauth_token was passed to the OAuth API.
109 $this->clientError(_('No oauth_token parameter provided.'));
112 // Check to make sure the token exists
113 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
115 if (empty($this->reqToken)) {
116 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
117 $this->clientError(_('Invalid request token.'));
120 // Check to make sure we haven't already authorized the token
121 if ($this->reqToken->state != 0) {
122 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
123 $this->clientError(_("Invalid request token."));
128 // make sure there's an app associated with this token
129 if (empty($this->app)) {
130 // TRANS: Client error given when an invalid request token was passed to the OAuth API.
131 $this->clientError(_('Invalid request token.'));
134 $name = $this->app->name;
140 function handlePost()
142 // check session token for CSRF protection.
144 $token = $this->trimmed('token');
146 if (!$token || $token != common_session_token()) {
148 _('There was a problem with your session token. Try again, please.'));
156 if (!common_logged_in()) {
158 // XXX Force credentials check?
162 $user = common_check_user($this->nickname, $this->password);
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();
172 if ($this->arg('allow')) {
175 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
177 // mark the req token as authorized
179 $this->store->authorize_token($this->oauthTokenParam);
180 } catch (Exception $e) {
181 $this->serverError($e->getMessage());
184 // associated the authorized req token with the user and the app
186 $appUser = new Oauth_application_user();
188 $appUser->profile_id = $user->id;
189 $appUser->application_id = $this->app->id;
191 // Note: do not copy the access type from the application.
192 // The access type should always be 0 when the OAuth app
193 // user record has a request token associated with it.
194 // Access type gets assigned once an access token has been
195 // granted. The OAuth app user record then gets updated
196 // with the new access token and access type.
198 $appUser->token = $this->oauthTokenParam;
199 $appUser->created = common_sql_now();
201 $result = $appUser->insert();
204 common_log_db_error($appUser, 'INSERT', __FILE__);
205 // TRANS: Server error given when a database error occurs inserting an OAuth application user.
206 $this->serverError(_('Database error inserting OAuth application user.'));
209 // If we have a callback redirect and provide the token
211 // Note: A callback specified in the app setup overrides whatever
212 // is passed in with the request.
214 if (!empty($this->app->callback_url)) {
215 $this->callback = $this->app->callback_url;
218 if (!empty($this->callback)) {
219 $targetUrl = $this->getCallback(
222 'oauth_token' => $this->oauthTokenParam,
223 'oauth_verifier' => $this->reqToken->verifier // 1.0a
227 // Redirect the user to the provided OAuth callback
228 common_redirect($targetUrl, 303);
229 } elseif ($this->app->type == 2) {
230 // Strangely, a web application seems to want to do the OOB
231 // workflow. Because no callback was specified anywhere.
235 "API OAuth - No callback provided for OAuth web client ID %s (%s) "
236 . "during authorization step. Falling back to OOB workflow.",
246 "The request token '%s' for OAuth application %s (%s) has been authorized.",
247 $this->oauthTokenParam,
253 // Otherwise, inform the user that the rt was authorized
254 $this->showAuthorized();
256 } else if ($this->arg('cancel')) {
259 $this->store->revoke_token($this->oauthTokenParam, 0);
260 $this->showCanceled();
261 } catch (Exception $e) {
262 $this->ServerError($e->getMessage());
266 // TRANS: Client error given on when invalid data was passed through a form in the OAuth API.
267 $this->clientError(_('Unexpected form submission.'));
271 function showForm($error=null)
273 $this->error = $error;
277 function showScripts()
279 parent::showScripts();
280 if (!common_logged_in()) {
281 $this->autofocus('nickname');
288 * @return string title of the page
293 // TRANS: Title for a page where a user can confirm/deny account access by an external application.
294 return _('An application would like to connect to your account');
298 * Shows the authorization form.
303 function showContent()
305 $this->elementStart('form', array('method' => 'post',
306 'id' => 'form_apioauthauthorize',
307 'class' => 'form_settings',
308 'action' => common_local_url('ApiOauthAuthorize')));
309 $this->elementStart('fieldset');
310 $this->element('legend', array('id' => 'apioauthauthorize_allowdeny'),
311 // TRANS: Fieldset legend.
312 _('Allow or deny access'));
314 $this->hidden('token', common_session_token());
315 $this->hidden('oauth_token', $this->oauthTokenParam);
316 $this->hidden('oauth_callback', $this->callback);
318 $this->elementStart('ul', 'form_data');
319 $this->elementStart('li');
320 $this->elementStart('p');
321 if (!empty($this->app->icon)) {
322 $this->element('img', array('src' => $this->app->icon));
325 $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
326 'access and update' : 'access';
328 // TRANS: User notification of external application requesting account access.
329 // TRANS: %1$s is the application name requesting access, %2$s is the organisation behind the application,
330 // TRANS: %3$s is the access type requested, %4$s is the StatusNet sitename.
331 $msg = _('The application <strong>%1$s</strong> by ' .
332 '<strong>%2$s</strong> would like the ability ' .
333 'to <strong>%3$s</strong> your %4$s account data. ' .
334 'You should only give access to your %4$s account ' .
335 'to third parties you trust.');
337 $this->raw(sprintf($msg,
339 $this->app->organization,
341 common_config('site', 'name')));
342 $this->elementEnd('p');
343 $this->elementEnd('li');
344 $this->elementEnd('ul');
346 if (!common_logged_in()) {
347 $this->elementStart('fieldset');
348 // TRANS: Fieldset legend.
349 $this->element('legend', null, _m('LEGEND','Account'));
350 $this->elementStart('ul', 'form_data');
351 $this->elementStart('li');
352 // TRANS: Field label on OAuth API authorisation form.
353 $this->input('nickname', _('Nickname'));
354 $this->elementEnd('li');
355 $this->elementStart('li');
356 // TRANS: Field label on OAuth API authorisation form.
357 $this->password('password', _('Password'));
358 $this->elementEnd('li');
359 $this->elementEnd('ul');
361 $this->elementEnd('fieldset');
364 $this->element('input', array('id' => 'cancel_submit',
365 'class' => 'submit submit form_action-primary',
368 // TRANS: Button text that when clicked will cancel the process of allowing access to an account
369 // TRANS: by an external application.
370 'value' => _m('BUTTON','Cancel')));
372 $this->element('input', array('id' => 'allow_submit',
373 'class' => 'submit submit form_action-secondary',
376 // TRANS: Button text that when clicked will allow access to an account by an external application.
377 'value' => _m('BUTTON','Allow')));
379 $this->elementEnd('fieldset');
380 $this->elementEnd('form');
384 * Instructions for using the form
386 * For "remembered" logins, we make the user re-login when they
387 * try to change settings. Different instructions for this case.
391 function getInstructions()
393 // TRANS: Form instructions.
394 return _('Authorize access to your account information.');
400 * Shows different login/register actions.
404 function showLocalNav()
414 function showSiteNotice()
422 * Show the form for posting a new notice
426 function showNoticeForm()
432 * Show a nice message confirming the authorization
433 * operation was canceled.
437 function showCanceled()
439 $info = new InfoAction(
440 // TRANS: Header for user notification after revoking OAuth access to an application.
441 _('Authorization canceled.'),
443 // TRANS: User notification after revoking OAuth access to an application.
444 // TRANS: %s is an OAuth token.
445 _('The request token %s has been revoked.'),
446 $this->oauthTokenParm
454 * Show a nice message that the authorization was successful.
455 * If the operation is out-of-band, show a pin.
459 function showAuthorized()
462 // TRANS: Header of user notification after authorising an application access to a profile.
463 // TRANS: %s is the authorised application name.
464 _("You have successfully authorized %s."),
469 // TRANS: Uer notification after authorising an application access to a profile.
470 // TRANS: %s is the authorised application name.
471 _('Please return to %s and enter the following security code to complete the process.'),
475 if ($this->reqToken->verified_callback == 'oob') {
476 $pin = new ApiOauthPinAction($title, $msg, $this->reqToken->verifier);
480 // NOTE: This would only happen if an application registered as
481 // a web application but sent in 'oob' for the oauth_callback
482 // parameter. Usually web apps will send in a callback and
483 // not use the pin-based workflow.
485 $info = new InfoAction(
488 $this->oauthTokenParam,
489 $this->reqToken->verifier
497 * Properly format the callback URL and parameters so it's
498 * suitable for a redirect in the OAuth dance
500 * @param string $url the URL
501 * @param array $params an array of parameters
503 * @return string $url a URL to use for redirecting to
505 function getCallback($url, $params)
507 foreach ($params as $k => $v) {
508 $url = $this->appendQueryVar(
510 OAuthUtil::urlencode_rfc3986($k),
511 OAuthUtil::urlencode_rfc3986($v)
519 * Append a new query parameter after any existing query
522 * @param string $url the URL
523 * @prarm string $k the parameter name
524 * @param string $v value of the paramter
526 * @return string $url the new URL with added parameter
528 function appendQueryVar($url, $k, $v) {
529 $url = preg_replace('/(.*)(\?|&)' . $k . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
530 $url = substr($url, 0, -1);
531 if (strpos($url, '?') === false) {
532 return ($url . '?' . $k . '=' . $v);
534 return ($url . '&' . $k . '=' . $v);