]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apioauthauthorize.php
* i18n/L10n fixes.
[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 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 require_once INSTALLDIR . '/lib/apioauth.php';
35 require_once INSTALLDIR . '/lib/info.php';
36
37 /**
38  * Authorize an Oputh request token
39  *
40  * @category API
41  * @package  StatusNet
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/
45  */
46 class ApiOauthAuthorizeAction extends Action
47 {
48     var $oauthTokenParam;
49     var $reqToken;
50     var $callback;
51     var $app;
52     var $nickname;
53     var $password;
54     var $store;
55
56     /**
57      * Is this a read-only action?
58      *
59      * @return boolean false
60      */
61
62     function isReadOnly($args)
63     {
64         return false;
65     }
66
67     function prepare($args)
68     {
69         parent::prepare($args);
70
71         $this->nickname        = $this->trimmed('nickname');
72         $this->password        = $this->arg('password');
73         $this->oauthTokenParam = $this->arg('oauth_token');
74         $this->mode            = $this->arg('mode');
75         $this->store           = new ApiStatusNetOAuthDataStore();
76
77         try {
78             $this->app = $this->store->getAppByRequestToken($this->oauthTokenParam);
79         } catch (Exception $e) {
80             $this->clientError($e->getMessage());
81         }
82
83         return true;
84     }
85
86     /**
87      * Handle input, produce output
88      *
89      * Switches on request method; either shows the form or handles its input.
90      *
91      * @param array $args $_REQUEST data
92      *
93      * @return void
94      */
95     function handle($args)
96     {
97         parent::handle($args);
98
99         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
100
101             $this->handlePost();
102
103         } else {
104
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.'));
109             } else {
110
111                 // Check to make sure the token exists
112                 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
113
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.'));
117                 } else {
118
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(_('Request token already authorized.'));
123                     }
124                 }
125             }
126
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.'));
131             }
132
133             $name = $this->app->name;
134
135             $this->showForm();
136         }
137     }
138
139     function handlePost()
140     {
141         // check session token for CSRF protection.
142
143         $token = $this->trimmed('token');
144
145         if (!$token || $token != common_session_token()) {
146             $this->showForm(
147                 // TRANS: Form validation error in API OAuth authorisation because of an invalid session token.
148                 _('There was a problem with your session token. Try again, please.'));
149             return;
150         }
151
152         // check creds
153
154         $user = null;
155
156         if (!common_logged_in()) {
157
158             // XXX Force credentials check?
159
160             // @fixme this should probably use a unified login form handler
161             $user = null;
162             if (Event::handle('StartOAuthLoginCheck', array($this, &$user))) {
163                 $user = common_check_user($this->nickname, $this->password);
164             }
165             Event::handle('EndOAuthLoginCheck', array($this, &$user));
166
167             if (empty($user)) {
168                 // TRANS: Form validation error given when an invalid username and/or password was passed to the OAuth API.
169                 $this->showForm(_("Invalid nickname / password!"));
170                 return;
171             }
172         } else {
173             $user = common_current_user();
174         }
175
176         // fetch the token
177         $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
178         assert(!empty($this->reqToken));
179
180         if ($this->arg('allow')) {
181             // mark the req token as authorized
182             try {
183                 $this->store->authorize_token($this->oauthTokenParam);
184             } catch (Exception $e) {
185                 $this->serverError($e->getMessage());
186             }
187
188             common_log(
189                 LOG_INFO,
190                 sprintf(
191                     "API OAuth - User %d (%s) has authorized request token %s for OAuth application %d (%s).",
192                     $user->id,
193                     $user->nickname,
194                     $this->reqToken->tok,
195                     $this->app->id,
196                     $this->app->name
197                 )
198             );
199
200             // XXX: Make sure we have a oauth_token_association table. The table
201             // is now in the main schema, but because it is being added with
202             // a point release, it's unlikely to be there. This code can be
203             // removed as of 1.0.
204             $this->ensureOauthTokenAssociationTable();
205
206             $tokenAssoc = new Oauth_token_association();
207
208             $tokenAssoc->profile_id     = $user->id;
209             $tokenAssoc->application_id = $this->app->id;
210             $tokenAssoc->token          = $this->oauthTokenParam;
211             $tokenAssoc->created        = common_sql_now();
212
213             $result = $tokenAssoc->insert();
214
215             if (!$result) {
216                 common_log_db_error($tokenAssoc, 'INSERT', __FILE__);
217                 // TRANS: Server error displayed when a database action fails.
218                 $this->serverError(_('Database error inserting oauth_token_association.'));
219             }
220
221             $callback = $this->getCallback();
222
223             if (!empty($callback) && $this->reqToken->verified_callback != 'oob') {
224                 $targetUrl = $this->buildCallbackUrl(
225                     $callback,
226                     array(
227                         'oauth_token'    => $this->oauthTokenParam,
228                         'oauth_verifier' => $this->reqToken->verifier // 1.0a
229                     )
230                 );
231
232                 common_log(LOG_INFO, "Redirecting to callback: $targetUrl");
233
234                 // Redirect the user to the provided OAuth callback
235                 common_redirect($targetUrl, 303);
236
237             } elseif ($this->app->type == 2) {
238                 // Strangely, a web application seems to want to do the OOB
239                 // workflow. Because no callback was specified anywhere.
240                 common_log(
241                     LOG_WARNING,
242                     sprintf(
243                         "API OAuth - No callback provided for OAuth web client ID %s (%s) "
244                          . "during authorization step. Falling back to OOB workflow.",
245                         $this->app->id,
246                         $this->app->name
247                     )
248                 );
249             }
250
251             // Otherwise, inform the user that the rt was authorized
252             $this->showAuthorized();
253         } else if ($this->arg('cancel')) {
254             common_log(
255                 LOG_INFO,
256                 sprintf(
257                     "API OAuth - User %d (%s) refused to authorize request token %s for OAuth application %d (%s).",
258                     $user->id,
259                     $user->nickname,
260                     $this->reqToken->tok,
261                     $this->app->id,
262                     $this->app->name
263                 )
264             );
265
266             try {
267                 $this->store->revoke_token($this->oauthTokenParam, 0);
268             } catch (Exception $e) {
269                 $this->ServerError($e->getMessage());
270             }
271
272             $callback = $this->getCallback();
273
274             // If there's a callback available, inform the consumer the user
275             // has refused authorization
276             if (!empty($callback) && $this->reqToken->verified_callback != 'oob') {
277                 $targetUrl = $this->buildCallbackUrl(
278                     $callback,
279                     array(
280                         'oauth_problem' => 'user_refused',
281                     )
282                 );
283
284                 common_log(LOG_INFO, "Redirecting to callback: $targetUrl");
285
286                 // Redirect the user to the provided OAuth callback
287                 common_redirect($targetUrl, 303);
288             }
289
290             // otherwise inform the user that authorization for the rt was declined
291             $this->showCanceled();
292
293         } else {
294             // TRANS: Client error given on when invalid data was passed through a form in the OAuth API.
295             $this->clientError(_('Unexpected form submission.'));
296         }
297     }
298
299     // XXX Remove this function when we hit 1.0
300     function ensureOauthTokenAssociationTable()
301     {
302         $schema = Schema::get();
303
304         $reqTokenCols = array(
305             new ColumnDef('profile_id', 'integer', null, true, 'PRI'),
306             new ColumnDef('application_id', 'integer', null, true, 'PRI'),
307             new ColumnDef('token', 'varchar', 255, true, 'PRI'),
308             new ColumnDef('created', 'datetime', null, false),
309             new ColumnDef(
310                 'modified',
311                 'timestamp',
312                 null,
313                 false,
314                 null,
315                 'CURRENT_TIMESTAMP',
316                 'on update CURRENT_TIMESTAMP'
317             )
318         );
319
320         $schema->ensureTable('oauth_token_association', $reqTokenCols);
321     }
322
323     /**
324      * Show body - override to add a special CSS class for the authorize
325      * page's "desktop mode" (minimal display)
326      *
327      * Calls template methods
328      *
329      * @return nothing
330      */
331     function showBody()
332     {
333         $bodyClasses = array();
334
335         if ($this->desktopMode()) {
336             $bodyClasses[] = 'oauth-desktop-mode';
337         }
338
339         if (common_current_user()) {
340             $bodyClasses[] = 'user_in';
341         }
342
343         $attrs = array('id' => strtolower($this->trimmed('action')));
344
345         if (!empty($bodyClasses)) {
346             $attrs['class'] = implode(' ', $bodyClasses);
347         }
348
349         $this->elementStart('body', $attrs);
350
351         $this->elementStart('div', array('id' => 'wrap'));
352         if (Event::handle('StartShowHeader', array($this))) {
353             $this->showHeader();
354             Event::handle('EndShowHeader', array($this));
355         }
356         $this->showCore();
357         if (Event::handle('StartShowFooter', array($this))) {
358             $this->showFooter();
359             Event::handle('EndShowFooter', array($this));
360         }
361         $this->elementEnd('div');
362         $this->showScripts();
363         $this->elementEnd('body');
364     }
365
366     function showForm($error=null)
367     {
368         $this->error = $error;
369         $this->showPage();
370     }
371
372     function showScripts()
373     {
374         parent::showScripts();
375         if (!common_logged_in()) {
376             $this->autofocus('nickname');
377         }
378     }
379
380     /**
381      * Title of the page
382      *
383      * @return string title of the page
384      */
385     function title()
386     {
387         // TRANS: Title for a page where a user can confirm/deny account access by an external application.
388         return _('An application would like to connect to your account');
389     }
390
391     /**
392      * Shows the authorization form.
393      *
394      * @return void
395      */
396     function showContent()
397     {
398         $this->elementStart('form', array('method' => 'post',
399                                           'id' => 'form_apioauthauthorize',
400                                           'class' => 'form_settings',
401                                           'action' => common_local_url('ApiOauthAuthorize')));
402         $this->elementStart('fieldset');
403         $this->element('legend', array('id' => 'apioauthauthorize_allowdeny'),
404                                  // TRANS: Fieldset legend.
405                                  _('Allow or deny access'));
406
407         $this->hidden('token', common_session_token());
408         $this->hidden('mode', $this->mode);
409         $this->hidden('oauth_token', $this->oauthTokenParam);
410         $this->hidden('oauth_callback', $this->callback);
411
412         $this->elementStart('ul', 'form_data');
413         $this->elementStart('li');
414         $this->elementStart('p');
415         if (!empty($this->app->icon) && $this->app->name != 'anonymous') {
416             $this->element('img', array('src' => $this->app->icon));
417         }
418
419         $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
420           'access and update' : 'access';
421
422         // TRANS: User notification of external application requesting account access.
423         // TRANS: %1$s is the application name requesting access, %2$s is the organisation behind the application,
424         // TRANS: %3$s is the access type requested, %4$s is the StatusNet sitename.
425         if ($this->app->name == 'anonymous') {
426         // Special message for the anonymous app and consumer
427             $msg = _('An application would like the ability ' .
428                  'to <strong>%3$s</strong> your %4$s account data. ' .
429                  'You should only give access to your %4$s account ' .
430                  'to third parties you trust.');
431         } else {
432             $msg = _('The application <strong>%1$s</strong> by ' .
433                      '<strong>%2$s</strong> would like the ability ' .
434                      'to <strong>%3$s</strong> your %4$s account data. ' .
435                      'You should only give access to your %4$s account ' .
436                      'to third parties you trust.');
437         }
438
439         $this->raw(sprintf($msg,
440                            $this->app->name,
441                            $this->app->organization,
442                            $access,
443                            common_config('site', 'name')));
444         $this->elementEnd('p');
445         $this->elementEnd('li');
446         $this->elementEnd('ul');
447
448         // quickie hack
449         $button = false;
450         if (!common_logged_in()) {
451             if (Event::handle('StartOAuthLoginForm', array($this, &$button))) {
452                 $this->elementStart('fieldset');
453                 // TRANS: Fieldset legend.
454                 $this->element('legend', null, _m('LEGEND','Account'));
455                 $this->elementStart('ul', 'form_data');
456                 $this->elementStart('li');
457                 // TRANS: Field label on OAuth API authorisation form.
458                 $this->input('nickname', _('Nickname'));
459                 $this->elementEnd('li');
460                 $this->elementStart('li');
461                 // TRANS: Field label on OAuth API authorisation form.
462                 $this->password('password', _('Password'));
463                 $this->elementEnd('li');
464                 $this->elementEnd('ul');
465
466                 $this->elementEnd('fieldset');
467             }
468             Event::handle('EndOAuthLoginForm', array($this, &$button));
469         }
470
471         $this->element('input', array('id' => 'cancel_submit',
472                                       'class' => 'submit submit form_action-primary',
473                                       'name' => 'cancel',
474                                       'type' => 'submit',
475                                       // TRANS: Button text that when clicked will cancel the process of allowing access to an account
476                                       // TRANS: by an external application.
477                                       'value' => _m('BUTTON','Cancel')));
478
479         $this->element('input', array('id' => 'allow_submit',
480                                       'class' => 'submit submit form_action-secondary',
481                                       'name' => 'allow',
482                                       'type' => 'submit',
483                                       // TRANS: Button text that when clicked will allow access to an account by an external application.
484                                       'value' => $button ? $button : _m('BUTTON','Allow')));
485
486         $this->elementEnd('fieldset');
487         $this->elementEnd('form');
488     }
489
490     /**
491      * Instructions for using the form
492      *
493      * For "remembered" logins, we make the user re-login when they
494      * try to change settings. Different instructions for this case.
495      *
496      * @return void
497      */
498     function getInstructions()
499     {
500         // TRANS: Form instructions.
501         return _('Authorize access to your account information.');
502     }
503
504     /**
505      * A local menu
506      *
507      * Shows different login/register actions.
508      *
509      * @return void
510      */
511     function showLocalNav()
512     {
513         // NOP
514     }
515
516     /*
517      * Checks to see if a the "mode" parameter is present in the request
518      * and set to "desktop". If it is, the page is meant to be displayed in
519      * a small frame of another application, and we should  suppress the
520      * header, aside, and footer.
521      */
522     function desktopMode()
523     {
524         if (isset($this->mode) && $this->mode == 'desktop') {
525             return true;
526         } else {
527             return false;
528         }
529     }
530
531     /*
532      * Override - suppress output in "desktop" mode
533      */
534     function showHeader()
535     {
536         if ($this->desktopMode() == false) {
537             parent::showHeader();
538         }
539     }
540
541     /*
542      * Override - suppress output in "desktop" mode
543      */
544     function showAside()
545     {
546         if ($this->desktopMode() == false) {
547             parent::showAside();
548         }
549     }
550
551     /*
552      * Override - suppress output in "desktop" mode
553      */
554     function showFooter()
555     {
556         if ($this->desktopMode() == false) {
557             parent::showFooter();
558         }
559     }
560
561     /**
562      * Show site notice.
563      *
564      * @return nothing
565      */
566     function showSiteNotice()
567     {
568         // NOP
569     }
570
571     /**
572      * Show notice form.
573      *
574      * Show the form for posting a new notice
575      *
576      * @return nothing
577      */
578     function showNoticeForm()
579     {
580         // NOP
581     }
582
583     /*
584      * Show a nice message confirming the authorization
585      * operation was canceled.
586      *
587      * @return nothing
588      */
589     function showCanceled()
590     {
591         $info = new InfoAction(
592             // TRANS: Header for user notification after revoking OAuth access to an application.
593             _('Authorization canceled.'),
594             sprintf(
595                 // TRANS: User notification after revoking OAuth access to an application.
596                 // TRANS: %s is an OAuth token.
597                 _('The request token %s has been revoked.'),
598                 $this->oauthTokenParam
599             )
600         );
601
602         $info->showPage();
603     }
604
605     /*
606      * Show a nice message that the authorization was successful.
607      * If the operation is out-of-band, show a pin.
608      *
609      * @return nothing
610      */
611     function showAuthorized()
612     {
613         $title = null;
614         $msg   = null;
615
616         if ($this->app->name == 'anonymous') {
617
618             $title =
619                 // TRANS: Title of the page notifying the user that an anonymous client application was successfully authorized to access the user's account with OAuth.
620                 _('You have successfully authorized the application');
621
622             $msg =
623                 // TRANS: Message notifying the user that an anonymous client application was successfully authorized to access the user's account with OAuth.
624                 _('Please return to the application and enter the following security code to complete the process.');
625
626         } else {
627
628             $title = sprintf(
629                 // TRANS: Title of the page notifying the user that the client application was successfully authorized to access the user's account with OAuth.
630                 // TRANS: %s is the authorised application name.
631                 _('You have successfully authorized %s'),
632                 $this->app->name
633             );
634
635             $msg = sprintf(
636                 // TRANS: Message notifying the user that the client application was successfully authorized to access the user's account with OAuth.
637                 // TRANS: %s is the authorised application name.
638                 _('Please return to %s and enter the following security code to complete the process.'),
639                 $this->app->name
640             );
641
642         }
643
644         if ($this->reqToken->verified_callback == 'oob') {
645             $pin = new ApiOauthPinAction(
646                 $title,
647                 $msg,
648                 $this->reqToken->verifier,
649                 $this->desktopMode()
650             );
651             $pin->showPage();
652         } else {
653             // NOTE: This would only happen if an application registered as
654             // a web application but sent in 'oob' for the oauth_callback
655             // parameter. Usually web apps will send in a callback and
656             // not use the pin-based workflow.
657
658             $info = new InfoAction(
659                 $title,
660                 $msg,
661                 $this->oauthTokenParam,
662                 $this->reqToken->verifier
663             );
664
665             $info->showPage();
666         }
667     }
668
669     /*
670      * Figure out what the callback should be
671      */
672     function getCallback()
673     {
674         $callback = null;
675
676         // Return the verified callback if we have one
677         if ($this->reqToken->verified_callback != 'oob') {
678
679             $callback = $this->reqToken->verified_callback;
680
681             // Otherwise return the callback that was provided when
682             // registering the app
683             if (empty($callback)) {
684
685                 common_debug(
686                     "No verified callback found for request token, using application callback: "
687                         . $this->app->callback_url,
688                      __FILE__
689                 );
690
691                 $callback = $this->app->callback_url;
692             }
693         }
694
695         return $callback;
696     }
697
698     /*
699      * Properly format the callback URL and parameters so it's
700      * suitable for a redirect in the OAuth dance
701      *
702      * @param string $url       the URL
703      * @param array  $params    an array of parameters
704      *
705      * @return string $url  a URL to use for redirecting to
706      */
707     function buildCallbackUrl($url, $params)
708     {
709         foreach ($params as $k => $v) {
710             $url = $this->appendQueryVar(
711                 $url,
712                 OAuthUtil::urlencode_rfc3986($k),
713                 OAuthUtil::urlencode_rfc3986($v)
714             );
715         }
716
717         return $url;
718     }
719
720     /*
721      * Append a new query parameter after any existing query
722      * parameters.
723      *
724      * @param string $url   the URL
725      * @prarm string $k     the parameter name
726      * @param string $v     value of the paramter
727      *
728      * @return string $url  the new URL with added parameter
729      */
730     function appendQueryVar($url, $k, $v) {
731         $url = preg_replace('/(.*)(\?|&)' . $k . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
732         $url = substr($url, 0, -1);
733         if (strpos($url, '?') === false) {
734             return ($url . '?' . $k . '=' . $v);
735         } else {
736             return ($url . '&' . $k . '=' . $v);
737         }
738     }
739 }