]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apioauthauthorize.php
XSS vulnerability when remote-subscribing
[quix0rs-gnu-social.git] / actions / apioauthauthorize.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Authorize an OAuth request token
6  *
7  * PHP version 5
8  *
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.
13  *
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.
18  *
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/>.
21  *
22  * @category  API
23  * @package   StatusNet
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/
28  */
29
30 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 /**
35  * Authorize an OAuth request token
36  *
37  * @category API
38  * @package  StatusNet
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/
42  */
43 class ApiOAuthAuthorizeAction extends ApiOAuthAction
44 {
45     var $oauthTokenParam;
46     var $reqToken;
47     var $callback;
48     var $app;
49     var $nickname;
50     var $password;
51     var $store;
52
53     /**
54      * Is this a read-only action?
55      *
56      * @return boolean false
57      */
58     function isReadOnly($args)
59     {
60         return false;
61     }
62
63     function prepare($args)
64     {
65         parent::prepare($args);
66
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();
72
73         try {
74             $this->app = $this->store->getAppByRequestToken($this->oauthTokenParam);
75         } catch (Exception $e) {
76             $this->clientError($e->getMessage());
77         }
78
79         return true;
80     }
81
82     /**
83      * Handle input, produce output
84      *
85      * Switches on request method; either shows the form or handles its input.
86      *
87      * @param array $args $_REQUEST data
88      *
89      * @return void
90      */
91     function handle($args)
92     {
93         parent::handle($args);
94
95         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
96
97             $this->handlePost();
98
99         } else {
100
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.'));
105             } else {
106
107                 // Check to make sure the token exists
108                 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
109
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.'));
113                 } else {
114
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.'));
119                     }
120                 }
121             }
122
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.'));
127             }
128
129             $name = $this->app->name;
130
131             $this->showForm();
132         }
133     }
134
135     function handlePost()
136     {
137         // check session token for CSRF protection.
138
139         $token = $this->trimmed('token');
140
141         if (!$token || $token != common_session_token()) {
142             $this->showForm(
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.'));
145             return;
146         }
147
148         // check creds
149
150         $user = null;
151
152         if (!common_logged_in()) {
153
154             // XXX Force credentials check?
155
156             // @fixme this should probably use a unified login form handler
157             $user = null;
158             if (Event::handle('StartOAuthLoginCheck', array($this, &$user))) {
159                 $user = common_check_user($this->nickname, $this->password);
160             }
161             Event::handle('EndOAuthLoginCheck', array($this, &$user));
162
163             if (empty($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!"));
166                 return;
167             }
168         } else {
169             $user = common_current_user();
170         }
171
172         // fetch the token
173         $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
174         assert(!empty($this->reqToken));
175
176         if ($this->arg('allow')) {
177             // mark the req token as authorized
178             try {
179                 $this->store->authorize_token($this->oauthTokenParam);
180             } catch (Exception $e) {
181                 $this->serverError($e->getMessage());
182             }
183
184             common_log(
185                 LOG_INFO,
186                 sprintf(
187                     "API OAuth - User %d (%s) has authorized request token %s for OAuth application %d (%s).",
188                     $user->id,
189                     $user->nickname,
190                     $this->reqToken->tok,
191                     $this->app->id,
192                     $this->app->name
193                 )
194             );
195
196             $tokenAssoc = new Oauth_token_association();
197
198             $tokenAssoc->profile_id     = $user->id;
199             $tokenAssoc->application_id = $this->app->id;
200             $tokenAssoc->token          = $this->oauthTokenParam;
201             $tokenAssoc->created        = common_sql_now();
202
203             $result = $tokenAssoc->insert();
204
205             if (!$result) {
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.'));
209             }
210
211             $callback = $this->getCallback();
212
213             if (!empty($callback) && $this->reqToken->verified_callback != 'oob') {
214                 $targetUrl = $this->buildCallbackUrl(
215                     $callback,
216                     array(
217                         'oauth_token'    => $this->oauthTokenParam,
218                         'oauth_verifier' => $this->reqToken->verifier // 1.0a
219                     )
220                 );
221
222                 common_log(LOG_INFO, "Redirecting to callback: $targetUrl");
223
224                 // Redirect the user to the provided OAuth callback
225                 common_redirect($targetUrl, 303);
226
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.
230                 common_log(
231                     LOG_WARNING,
232                     sprintf(
233                         "API OAuth - No callback provided for OAuth web client ID %s (%s) "
234                          . "during authorization step. Falling back to OOB workflow.",
235                         $this->app->id,
236                         $this->app->name
237                     )
238                 );
239             }
240
241             // Otherwise, inform the user that the rt was authorized
242             $this->showAuthorized();
243         } else if ($this->arg('cancel')) {
244             common_log(
245                 LOG_INFO,
246                 sprintf(
247                     "API OAuth - User %d (%s) refused to authorize request token %s for OAuth application %d (%s).",
248                     $user->id,
249                     $user->nickname,
250                     $this->reqToken->tok,
251                     $this->app->id,
252                     $this->app->name
253                 )
254             );
255
256             try {
257                 $this->store->revoke_token($this->oauthTokenParam, 0);
258             } catch (Exception $e) {
259                 $this->ServerError($e->getMessage());
260             }
261
262             $callback = $this->getCallback();
263
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(
268                     $callback,
269                     array(
270                         'oauth_problem' => 'user_refused',
271                     )
272                 );
273
274                 common_log(LOG_INFO, "Redirecting to callback: $targetUrl");
275
276                 // Redirect the user to the provided OAuth callback
277                 common_redirect($targetUrl, 303);
278             }
279
280             // otherwise inform the user that authorization for the rt was declined
281             $this->showCanceled();
282
283         } else {
284             // TRANS: Client error given on when invalid data was passed through a form in the OAuth API.
285             $this->clientError(_('Unexpected form submission.'));
286         }
287     }
288
289     /**
290      * Show body - override to add a special CSS class for the authorize
291      * page's "desktop mode" (minimal display)
292      *
293      * Calls template methods
294      *
295      * @return nothing
296      */
297     function showBody()
298     {
299         $bodyClasses = array();
300
301         if ($this->desktopMode()) {
302             $bodyClasses[] = 'oauth-desktop-mode';
303         }
304
305         if (common_current_user()) {
306             $bodyClasses[] = 'user_in';
307         }
308
309         $attrs = array('id' => strtolower($this->trimmed('action')));
310
311         if (!empty($bodyClasses)) {
312             $attrs['class'] = implode(' ', $bodyClasses);
313         }
314
315         $this->elementStart('body', $attrs);
316
317         $this->elementStart('div', array('id' => 'wrap'));
318         if (Event::handle('StartShowHeader', array($this))) {
319             $this->showHeader();
320             Event::handle('EndShowHeader', array($this));
321         }
322         $this->showCore();
323         if (Event::handle('StartShowFooter', array($this))) {
324             $this->showFooter();
325             Event::handle('EndShowFooter', array($this));
326         }
327         $this->elementEnd('div');
328         $this->showScripts();
329         $this->elementEnd('body');
330     }
331
332     function showForm($error=null)
333     {
334         $this->error = $error;
335         $this->showPage();
336     }
337
338     function showScripts()
339     {
340         parent::showScripts();
341         if (!common_logged_in()) {
342             $this->autofocus('nickname');
343         }
344     }
345
346     /**
347      * Title of the page
348      *
349      * @return string title of the page
350      */
351     function title()
352     {
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');
355     }
356
357     /**
358      * Shows the authorization form.
359      *
360      * @return void
361      */
362     function showContent()
363     {
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'));
372
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);
377
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));
383         }
384
385         $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
386           'access and update' : 'access';
387
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.');
396         } else {
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.');
405         }
406
407         $this->raw(sprintf($msg,
408                            $this->app->name,
409                            $this->app->organization,
410                            $access,
411                            common_config('site', 'name')));
412         $this->elementEnd('p');
413         $this->elementEnd('li');
414         $this->elementEnd('ul');
415
416         // quickie hack
417         $button = false;
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');
433
434                 $this->elementEnd('fieldset');
435             }
436             Event::handle('EndOAuthLoginForm', array($this, &$button));
437         }
438
439         $this->element('input', array('id' => 'cancel_submit',
440                                       'class' => 'submit submit form_action-primary',
441                                       'name' => 'cancel',
442                                       'type' => 'submit',
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')));
446
447         $this->element('input', array('id' => 'allow_submit',
448                                       'class' => 'submit submit form_action-secondary',
449                                       'name' => 'allow',
450                                       'type' => 'submit',
451                                       // TRANS: Button text that when clicked will allow access to an account by an external application.
452                                       'value' => $button ? $button : _m('BUTTON','Allow')));
453
454         $this->elementEnd('fieldset');
455         $this->elementEnd('form');
456     }
457
458     /**
459      * Instructions for using the form
460      *
461      * For "remembered" logins, we make the user re-login when they
462      * try to change settings. Different instructions for this case.
463      *
464      * @return void
465      */
466     function getInstructions()
467     {
468         // TRANS: Form instructions.
469         return _('Authorize access to your account information.');
470     }
471
472     /**
473      * A local menu
474      *
475      * Shows different login/register actions.
476      *
477      * @return void
478      */
479     function showLocalNav()
480     {
481         // NOP
482     }
483
484     /*
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.
489      */
490     function desktopMode()
491     {
492         if (isset($this->mode) && $this->mode == 'desktop') {
493             return true;
494         } else {
495             return false;
496         }
497     }
498
499     /*
500      * Override - suppress output in "desktop" mode
501      */
502     function showHeader()
503     {
504         if ($this->desktopMode() == false) {
505             parent::showHeader();
506         }
507     }
508
509     /*
510      * Override - suppress output in "desktop" mode
511      */
512     function showAside()
513     {
514         if ($this->desktopMode() == false) {
515             parent::showAside();
516         }
517     }
518
519     /*
520      * Override - suppress output in "desktop" mode
521      */
522     function showFooter()
523     {
524         if ($this->desktopMode() == false) {
525             parent::showFooter();
526         }
527     }
528
529     /**
530      * Show site notice.
531      *
532      * @return nothing
533      */
534     function showSiteNotice()
535     {
536         // NOP
537     }
538
539     /**
540      * Show notice form.
541      *
542      * Show the form for posting a new notice
543      *
544      * @return nothing
545      */
546     function showNoticeForm()
547     {
548         // NOP
549     }
550
551     /*
552      * Show a nice message confirming the authorization
553      * operation was canceled.
554      *
555      * @return nothing
556      */
557     function showCanceled()
558     {
559         $info = new InfoAction(
560             // TRANS: Header for user notification after revoking OAuth access to an application.
561             _('Authorization canceled.'),
562             sprintf(
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
567             )
568         );
569
570         $info->showPage();
571     }
572
573     /*
574      * Show a nice message that the authorization was successful.
575      * If the operation is out-of-band, show a pin.
576      *
577      * @return nothing
578      */
579     function showAuthorized()
580     {
581         $title = null;
582         $msg   = null;
583
584         if ($this->app->name == 'anonymous') {
585
586             $title =
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');
589
590             $msg =
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.');
593
594         } else {
595
596             $title = sprintf(
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'),
600                 $this->app->name
601             );
602
603             $msg = sprintf(
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.'),
607                 $this->app->name
608             );
609
610         }
611
612         if ($this->reqToken->verified_callback == 'oob') {
613             $pin = new ApiOAuthPinAction(
614                 $title,
615                 $msg,
616                 $this->reqToken->verifier,
617                 $this->desktopMode()
618             );
619             $pin->showPage();
620         } else {
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.
625
626             $info = new InfoAction(
627                 $title,
628                 $msg,
629                 $this->oauthTokenParam,
630                 $this->reqToken->verifier
631             );
632
633             $info->showPage();
634         }
635     }
636
637     /*
638      * Figure out what the callback should be
639      */
640     function getCallback()
641     {
642         $callback = null;
643
644         // Return the verified callback if we have one
645         if ($this->reqToken->verified_callback != 'oob') {
646
647             $callback = $this->reqToken->verified_callback;
648
649             // Otherwise return the callback that was provided when
650             // registering the app
651             if (empty($callback)) {
652
653                 common_debug(
654                     "No verified callback found for request token, using application callback: "
655                         . $this->app->callback_url,
656                      __FILE__
657                 );
658
659                 $callback = $this->app->callback_url;
660             }
661         }
662
663         return $callback;
664     }
665
666     /*
667      * Properly format the callback URL and parameters so it's
668      * suitable for a redirect in the OAuth dance
669      *
670      * @param string $url       the URL
671      * @param array  $params    an array of parameters
672      *
673      * @return string $url  a URL to use for redirecting to
674      */
675     function buildCallbackUrl($url, $params)
676     {
677         foreach ($params as $k => $v) {
678             $url = $this->appendQueryVar(
679                 $url,
680                 OAuthUtil::urlencode_rfc3986($k),
681                 OAuthUtil::urlencode_rfc3986($v)
682             );
683         }
684
685         return $url;
686     }
687
688     /*
689      * Append a new query parameter after any existing query
690      * parameters.
691      *
692      * @param string $url   the URL
693      * @prarm string $k     the parameter name
694      * @param string $v     value of the paramter
695      *
696      * @return string $url  the new URL with added parameter
697      */
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);
703         } else {
704             return ($url . '&' . $k . '=' . $v);
705         }
706     }
707 }