]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apioauthauthorize.php
Fix bad reference.
[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                 _('There was a problem with your session token. Try again, please.'));
148             return;
149         }
150
151         // check creds
152
153         $user = null;
154
155         if (!common_logged_in()) {
156
157             // XXX Force credentials check?
158
159             // @fixme this should probably use a unified login form handler
160             $user = null;
161             if (Event::handle('StartOAuthLoginCheck', array($this, &$user))) {
162                 $user = common_check_user($this->nickname, $this->password);
163             }
164             Event::handle('EndOAuthLoginCheck', array($this, &$user));
165
166             if (empty($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!"));
169                 return;
170             }
171         } else {
172             $user = common_current_user();
173         }
174
175         if ($this->arg('allow')) {
176
177             common_debug("allow");
178             // fetch the token
179             $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
180
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                     "The request token '%s' for OAuth application %s (%s) has been authorized.",
192                     $this->oauthTokenParam,
193                     $this->app->id,
194                     $this->app->name
195                 )
196             );
197
198             // XXX: Make sure we have a oauth_token_association table. The table
199             // is now in the main schema, but because it is being added with
200             // a point release, it's unlikely to be there. This code can be
201             // removed as of 1.0.
202             $this->ensureOauthTokenAssociationTable();
203
204             $tokenAssoc = new Oauth_token_association();
205
206             $tokenAssoc->profile_id     = $user->id;
207             $tokenAssoc->application_id = $this->app->id;
208             $tokenAssoc->token          = $this->oauthTokenParam;
209             $tokenAssoc->created        = common_sql_now();
210
211             $result = $tokenAssoc->insert();
212
213             if (!$result) {
214                 common_log_db_error($tokenAssoc, 'INSERT', __FILE__);
215                 // TRANS: Server error displayed when a database action fails.
216                 $this->serverError(_('Database error inserting oauth_token_association.'));
217             }
218
219             $callback = $this->getCallback();
220
221             if (!empty($callback) && $this->reqToken->verified_callback != 'oob') {
222                 $targetUrl = $this->buildCallbackUrl(
223                     $callback,
224                     array(
225                         'oauth_token'    => $this->oauthTokenParam,
226                         'oauth_verifier' => $this->reqToken->verifier // 1.0a
227                     )
228                 );
229
230                 common_log(
231                     LOG_INFO, 
232                     "API OAuth - Request token authorized; doing callback to $targetUrl"
233                 );
234
235                 // Redirect the user to the provided OAuth callback
236                 common_redirect($targetUrl, 303);
237
238             } elseif ($this->app->type == 2) {
239                 // Strangely, a web application seems to want to do the OOB
240                 // workflow. Because no callback was specified anywhere.
241                 common_log(
242                     LOG_WARNING,
243                     sprintf(
244                         "API OAuth - No callback provided for OAuth web client ID %s (%s) "
245                          . "during authorization step. Falling back to OOB workflow.",
246                         $this->app->id,
247                         $this->app->name
248                     )
249                 );
250             }
251
252             // Otherwise, inform the user that the rt was authorized
253             $this->showAuthorized();
254
255         } else if ($this->arg('cancel')) {
256
257             try {
258                 $this->store->revoke_token($this->oauthTokenParam, 0);
259                 $this->showCanceled();
260             } catch (Exception $e) {
261                 $this->ServerError($e->getMessage());
262             }
263
264         } else {
265             // TRANS: Client error given on when invalid data was passed through a form in the OAuth API.
266             $this->clientError(_('Unexpected form submission.'));
267         }
268     }
269
270     // XXX Remove this function when we hit 1.0
271     function ensureOauthTokenAssociationTable()
272     {
273         $schema = Schema::get();
274
275         $reqTokenCols = array(
276             new ColumnDef('profile_id', 'integer', null, true, 'PRI'),
277             new ColumnDef('application_id', 'integer', null, true, 'PRI'),
278             new ColumnDef('token', 'varchar', 255, true, 'PRI'),
279             new ColumnDef('created', 'datetime', null, false),
280             new ColumnDef(
281                 'modified',
282                 'timestamp',
283                 null,
284                 false,
285                 null,
286                 'CURRENT_TIMESTAMP',
287                 'on update CURRENT_TIMESTAMP'
288             )
289         );
290
291         $schema->ensureTable('oauth_token_association', $reqTokenCols);
292     }
293
294
295     /**
296      * Override to add some special (more compact) styling when the page is
297      * being displayed in desktop mode.
298      *
299      * @return nothing
300      */
301     function showStylesheets()
302     {
303         parent::showStyleSheets();
304
305         if ($this->desktopMode()) {
306             $this->style('#wrap {min-width: 500px; } #content {width: 480px; padding: 10px;} fieldset {margin-bottom: 10px !important;}</style>');
307         }
308     }
309
310     function showForm($error=null)
311     {
312         $this->error = $error;
313         $this->showPage();
314     }
315
316     function showScripts()
317     {
318         parent::showScripts();
319         if (!common_logged_in()) {
320             $this->autofocus('nickname');
321         }
322     }
323
324     /**
325      * Title of the page
326      *
327      * @return string title of the page
328      */
329     function title()
330     {
331         // TRANS: Title for a page where a user can confirm/deny account access by an external application.
332         return _('An application would like to connect to your account');
333     }
334
335     /**
336      * Shows the authorization form.
337      *
338      * @return void
339      */
340     function showContent()
341     {
342         $this->elementStart('form', array('method' => 'post',
343                                           'id' => 'form_apioauthauthorize',
344                                           'class' => 'form_settings',
345                                           'action' => common_local_url('apioauthauthorize')));
346         $this->elementStart('fieldset');
347         $this->element('legend', array('id' => 'apioauthauthorize_allowdeny'),
348                                  // TRANS: Fieldset legend.
349                                  _('Allow or deny access'));
350
351         $this->hidden('token', common_session_token());
352         $this->hidden('oauth_token', $this->oauthTokenParam);
353         $this->hidden('oauth_callback', $this->callback);
354
355         $this->elementStart('ul', 'form_data');
356         $this->elementStart('li');
357         $this->elementStart('p');
358         if (!empty($this->app->icon)) {
359             $this->element('img', array('src' => $this->app->icon));
360         }
361
362         $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
363           'access and update' : 'access';
364
365         // TRANS: User notification of external application requesting account access.
366         // TRANS: %1$s is the application name requesting access, %2$s is the organisation behind the application,
367         // TRANS: %3$s is the access type requested, %4$s is the StatusNet sitename.
368         $msg = _('The application <strong>%1$s</strong> by ' .
369                  '<strong>%2$s</strong> would like the ability ' .
370                  'to <strong>%3$s</strong> your %4$s account data. ' .
371                  'You should only give access to your %4$s account ' .
372                  'to third parties you trust.');
373
374         $this->raw(sprintf($msg,
375                            $this->app->name,
376                            $this->app->organization,
377                            $access,
378                            common_config('site', 'name')));
379         $this->elementEnd('p');
380         $this->elementEnd('li');
381         $this->elementEnd('ul');
382
383         // quickie hack
384         $button = false;
385         if (!common_logged_in()) {
386             if (Event::handle('StartOAuthLoginForm', array($this, &$button))) {
387                 $this->elementStart('fieldset');
388                 // TRANS: Fieldset legend.
389                 $this->element('legend', null, _m('LEGEND','Account'));
390                 $this->elementStart('ul', 'form_data');
391                 $this->elementStart('li');
392                 // TRANS: Field label on OAuth API authorisation form.
393                 $this->input('nickname', _('Nickname'));
394                 $this->elementEnd('li');
395                 $this->elementStart('li');
396                 // TRANS: Field label on OAuth API authorisation form.
397                 $this->password('password', _('Password'));
398                 $this->elementEnd('li');
399                 $this->elementEnd('ul');
400
401                 $this->elementEnd('fieldset');
402             }
403             Event::handle('EndOAuthLoginForm', array($this, &$button));
404         }
405
406         $this->element('input', array('id' => 'cancel_submit',
407                                       'class' => 'submit submit form_action-primary',
408                                       'name' => 'cancel',
409                                       'type' => 'submit',
410                                       // TRANS: Button text that when clicked will cancel the process of allowing access to an account
411                                       // TRANS: by an external application.
412                                       'value' => _m('BUTTON','Cancel')));
413
414         $this->element('input', array('id' => 'allow_submit',
415                                       'class' => 'submit submit form_action-secondary',
416                                       'name' => 'allow',
417                                       'type' => 'submit',
418                                       // TRANS: Button text that when clicked will allow access to an account by an external application.
419                                       'value' => $button ? $button : _m('BUTTON','Allow')));
420
421         $this->elementEnd('fieldset');
422         $this->elementEnd('form');
423     }
424
425     /**
426      * Instructions for using the form
427      *
428      * For "remembered" logins, we make the user re-login when they
429      * try to change settings. Different instructions for this case.
430      *
431      * @return void
432      */
433     function getInstructions()
434     {
435         // TRANS: Form instructions.
436         return _('Authorize access to your account information.');
437     }
438
439     /**
440      * A local menu
441      *
442      * Shows different login/register actions.
443      *
444      * @return void
445      */
446     function showLocalNav()
447     {
448         // NOP
449     }
450
451     /*
452      * Checks to see if a the "mode" parameter is present in the request
453      * and set to "desktop". If it is, the page is meant to be displayed in
454      * a small frame of another application, and we should  suppress the
455      * header, aside, and footer.
456      */
457     function desktopMode()
458     {
459         if (isset($this->mode) && $this->mode == 'desktop') {
460             return true;
461         } else {
462             return false;
463         }
464     }
465
466     /*
467      * Override - suppress output in "desktop" mode
468      */
469     function showHeader()
470     {
471         if ($this->desktopMode() == false) {
472             parent::showHeader();
473         }
474     }
475
476     /*
477      * Override - suppress output in "desktop" mode
478      */
479     function showAside()
480     {
481         if ($this->desktopMode() == false) {
482             parent::showAside();
483         }
484     }
485
486     /*
487      * Override - suppress output in "desktop" mode
488      */
489     function showFooter()
490     {
491         if ($this->desktopMode() == false) {
492             parent::showFooter();
493         }
494     }
495
496     /**
497      * Show site notice.
498      *
499      * @return nothing
500      */
501     function showSiteNotice()
502     {
503         // NOP
504     }
505
506     /**
507      * Show notice form.
508      *
509      * Show the form for posting a new notice
510      *
511      * @return nothing
512      */
513     function showNoticeForm()
514     {
515         // NOP
516     }
517
518     /*
519      * Show a nice message confirming the authorization
520      * operation was canceled.
521      *
522      * @return nothing
523      */
524     function showCanceled()
525     {
526         $info = new InfoAction(
527             // TRANS: Header for user notification after revoking OAuth access to an application.
528             _('Authorization canceled.'),
529             sprintf(
530                 // TRANS: User notification after revoking OAuth access to an application.
531                 // TRANS: %s is an OAuth token.
532                 _('The request token %s has been revoked.'),
533                 $this->oauthTokenParm
534             )
535         );
536
537         $info->showPage();
538     }
539
540     /*
541      * Show a nice message that the authorization was successful.
542      * If the operation is out-of-band, show a pin.
543      *
544      * @return nothing
545      */
546     function showAuthorized()
547     {
548         $title = sprintf(
549            // TRANS: Header of user notification after authorising an application access to a profile.
550            // TRANS: %s is the authorised application name.
551             _("You have successfully authorized %s."),
552             $this->app->name
553         );
554
555         $msg = sprintf(
556             // TRANS: Uer notification after authorising an application access to a profile.
557             // TRANS: %s is the authorised application name.
558             _('Please return to %s and enter the following security code to complete the process.'),
559             $this->app->name
560         );
561
562         if ($this->reqToken->verified_callback == 'oob') {
563             $pin = new ApiOauthPinAction($title, $msg, $this->reqToken->verifier);
564             $pin->showPage();
565         } else {
566
567             // NOTE: This would only happen if an application registered as
568             // a web application but sent in 'oob' for the oauth_callback
569             // parameter. Usually web apps will send in a callback and
570             // not use the pin-based workflow.
571
572             $info = new InfoAction(
573                 $title,
574                 $msg,
575                 $this->oauthTokenParam,
576                 $this->reqToken->verifier
577             );
578
579             $info->showPage();
580         }
581     }
582
583     /*
584      * Figure out what the callback should be
585      */
586     function getCallback()
587     {
588         $callback = null;
589
590         // Return the verified callback if we have one
591         if ($this->app->type == 2) {
592
593             $callback = $this->reqToken->verified_callback;
594
595             // Otherwise return the callback that was provided when
596             // registering the app
597             if (empty($callback)) {
598
599                 common_debug(
600                     "No verified callback found for request token, using application callback: "
601                         . $this->app->callback_url,
602                      __FILE__
603                 );
604
605                 $callback = $this->app->callback_url;
606             }
607
608         }
609
610         return $callback;
611     }
612
613     /*
614      * Properly format the callback URL and parameters so it's
615      * suitable for a redirect in the OAuth dance
616      *
617      * @param string $url       the URL
618      * @param array  $params    an array of parameters
619      *
620      * @return string $url  a URL to use for redirecting to
621      */
622     function buildCallbackUrl($url, $params)
623     {
624         foreach ($params as $k => $v) {
625             $url = $this->appendQueryVar(
626                 $url,
627                 OAuthUtil::urlencode_rfc3986($k),
628                 OAuthUtil::urlencode_rfc3986($v)
629             );
630         }
631
632         return $url;
633     }
634
635     /*
636      * Append a new query parameter after any existing query
637      * parameters.
638      *
639      * @param string $url   the URL
640      * @prarm string $k     the parameter name
641      * @param string $v     value of the paramter
642      *
643      * @return string $url  the new URL with added parameter
644      */
645     function appendQueryVar($url, $k, $v) {
646         $url = preg_replace('/(.*)(\?|&)' . $k . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
647         $url = substr($url, 0, -1);
648         if (strpos($url, '?') === false) {
649             return ($url . '?' . $k . '=' . $v);
650         } else {
651             return ($url . '&' . $k . '=' . $v);
652         }
653     }
654 }