]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apioauthauthorize.php
Change OAuth authorization page's action name to be inline with
[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->callback        = $this->arg('oauth_callback');
75         $this->mode            = $this->arg('mode');
76         $this->store           = new ApiStatusNetOAuthDataStore();
77
78         try {
79             $this->app = $this->store->getAppByRequestToken($this->oauthTokenParam);
80         } catch (Exception $e) {
81             $this->clientError($e->getMessage());
82         }
83
84         return true;
85     }
86
87     /**
88      * Handle input, produce output
89      *
90      * Switches on request method; either shows the form or handles its input.
91      *
92      * @param array $args $_REQUEST data
93      *
94      * @return void
95      */
96     function handle($args)
97     {
98         parent::handle($args);
99
100         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
101
102             $this->handlePost();
103
104         } else {
105
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.'));
110             } else {
111
112                 // Check to make sure the token exists
113                 $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
114
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.'));
118                 } else {
119
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(_('Request token already authorized.'));
124                     }
125                 }
126             }
127
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.'));
132             }
133
134             $name = $this->app->name;
135
136             $this->showForm();
137         }
138     }
139
140     function handlePost()
141     {
142         // check session token for CSRF protection.
143
144         $token = $this->trimmed('token');
145
146         if (!$token || $token != common_session_token()) {
147             $this->showForm(
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         if ($this->arg('allow')) {
177
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             // XXX: Make sure we have a oauth_token_association table. The table
189             // is now in the main schema, but because it is being added with
190             // a point release, it's unlikely to be there. This code can be
191             // removed as of 1.0.
192             $this->ensureOauthTokenAssociationTable();
193
194             $tokenAssoc = new Oauth_token_association();
195
196             $tokenAssoc->profile_id     = $user->id;
197             $tokenAssoc->application_id = $this->app->id;
198             $tokenAssoc->token          = $this->oauthTokenParam;
199             $tokenAssoc->created        = common_sql_now();
200
201             $result = $tokenAssoc->insert();
202
203             if (!$result) {
204                 common_log_db_error($tokenAssoc, 'INSERT', __FILE__);
205                 // TRANS: Server error displayed when a database action fails.
206                 $this->serverError(_('Database error inserting oauth_token_association.'));
207             }
208
209             // If we have a callback redirect and provide the token
210
211             // Note: A callback specified in the app setup overrides whatever
212             // is passed in with the request.
213
214             if (!empty($this->app->callback_url)) {
215                 $this->callback = $this->app->callback_url;
216             }
217
218             if (!empty($this->callback)) {
219                 $targetUrl = $this->getCallback(
220                     $this->callback,
221                     array(
222                         'oauth_token'    => $this->oauthTokenParam,
223                         'oauth_verifier' => $this->reqToken->verifier // 1.0a
224                     )
225                 );
226
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.
232                 common_log(
233                     LOG_WARNING,
234                     sprintf(
235                         "API OAuth - No callback provided for OAuth web client ID %s (%s) "
236                          . "during authorization step. Falling back to OOB workflow.",
237                         $this->app->id,
238                         $this->app->name
239                     )
240                 );
241             }
242
243             common_log(
244                 LOG_INFO,
245                 sprintf(
246                     "The request token '%s' for OAuth application %s (%s) has been authorized.",
247                     $this->oauthTokenParam,
248                     $this->app->id,
249                     $this->app->name
250                 )
251             );
252
253             // Otherwise, inform the user that the rt was authorized
254             $this->showAuthorized();
255         } else if ($this->arg('cancel')) {
256             try {
257                 $this->store->revoke_token($this->oauthTokenParam, 0);
258                 $this->showCanceled();
259             } catch (Exception $e) {
260                 $this->ServerError($e->getMessage());
261             }
262         } else {
263             // TRANS: Client error given on when invalid data was passed through a form in the OAuth API.
264             $this->clientError(_('Unexpected form submission.'));
265         }
266     }
267
268     // XXX Remove this function when we hit 1.0
269     function ensureOauthTokenAssociationTable()
270     {
271         $schema = Schema::get();
272
273         $reqTokenCols = array(
274             new ColumnDef('profile_id', 'integer', null, true, 'PRI'),
275             new ColumnDef('application_id', 'integer', null, true, 'PRI'),
276             new ColumnDef('token', 'varchar', 255, true, 'PRI'),
277             new ColumnDef('created', 'datetime', null, false),
278             new ColumnDef(
279                 'modified',
280                 'timestamp',
281                 null,
282                 false,
283                 null,
284                 'CURRENT_TIMESTAMP',
285                 'on update CURRENT_TIMESTAMP'
286             )
287         );
288
289         $schema->ensureTable('oauth_token_association', $reqTokenCols);
290     }
291
292     function showForm($error=null)
293     {
294         $this->error = $error;
295         $this->showPage();
296     }
297
298     function showScripts()
299     {
300         parent::showScripts();
301         if (!common_logged_in()) {
302             $this->autofocus('nickname');
303         }
304     }
305
306     /**
307      * Title of the page
308      *
309      * @return string title of the page
310      */
311     function title()
312     {
313         // TRANS: Title for a page where a user can confirm/deny account access by an external application.
314         return _('An application would like to connect to your account');
315     }
316
317     /**
318      * Shows the authorization form.
319      *
320      * @return void
321      */
322     function showContent()
323     {
324         $this->elementStart('form', array('method' => 'post',
325                                           'id' => 'form_apioauthauthorize',
326                                           'class' => 'form_settings',
327                                           'action' => common_local_url('ApiOauthAuthorize')));
328         $this->elementStart('fieldset');
329         $this->element('legend', array('id' => 'apioauthauthorize_allowdeny'),
330                                  // TRANS: Fieldset legend.
331                                  _('Allow or deny access'));
332
333         $this->hidden('token', common_session_token());
334         $this->hidden('oauth_token', $this->oauthTokenParam);
335         $this->hidden('oauth_callback', $this->callback);
336
337         $this->elementStart('ul', 'form_data');
338         $this->elementStart('li');
339         $this->elementStart('p');
340         if (!empty($this->app->icon)) {
341             $this->element('img', array('src' => $this->app->icon));
342         }
343
344         $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
345           'access and update' : 'access';
346
347         // TRANS: User notification of external application requesting account access.
348         // TRANS: %1$s is the application name requesting access, %2$s is the organisation behind the application,
349         // TRANS: %3$s is the access type requested, %4$s is the StatusNet sitename.
350         $msg = _('The application <strong>%1$s</strong> by ' .
351                  '<strong>%2$s</strong> would like the ability ' .
352                  'to <strong>%3$s</strong> your %4$s account data. ' .
353                  'You should only give access to your %4$s account ' .
354                  'to third parties you trust.');
355
356         $this->raw(sprintf($msg,
357                            $this->app->name,
358                            $this->app->organization,
359                            $access,
360                            common_config('site', 'name')));
361         $this->elementEnd('p');
362         $this->elementEnd('li');
363         $this->elementEnd('ul');
364
365         // quickie hack
366         $button = false;
367         if (!common_logged_in()) {
368             if (Event::handle('StartOAuthLoginForm', array($this, &$button))) {
369                 $this->elementStart('fieldset');
370                 // TRANS: Fieldset legend.
371                 $this->element('legend', null, _m('LEGEND','Account'));
372                 $this->elementStart('ul', 'form_data');
373                 $this->elementStart('li');
374                 // TRANS: Field label on OAuth API authorisation form.
375                 $this->input('nickname', _('Nickname'));
376                 $this->elementEnd('li');
377                 $this->elementStart('li');
378                 // TRANS: Field label on OAuth API authorisation form.
379                 $this->password('password', _('Password'));
380                 $this->elementEnd('li');
381                 $this->elementEnd('ul');
382
383                 $this->elementEnd('fieldset');
384             }
385             Event::handle('EndOAuthLoginForm', array($this, &$button));
386         }
387
388         $this->element('input', array('id' => 'cancel_submit',
389                                       'class' => 'submit submit form_action-primary',
390                                       'name' => 'cancel',
391                                       'type' => 'submit',
392                                       // TRANS: Button text that when clicked will cancel the process of allowing access to an account
393                                       // TRANS: by an external application.
394                                       'value' => _m('BUTTON','Cancel')));
395
396         $this->element('input', array('id' => 'allow_submit',
397                                       'class' => 'submit submit form_action-secondary',
398                                       'name' => 'allow',
399                                       'type' => 'submit',
400                                       // TRANS: Button text that when clicked will allow access to an account by an external application.
401                                       'value' => $button ? $button : _m('BUTTON','Allow')));
402
403         $this->elementEnd('fieldset');
404         $this->elementEnd('form');
405     }
406
407     /**
408      * Instructions for using the form
409      *
410      * For "remembered" logins, we make the user re-login when they
411      * try to change settings. Different instructions for this case.
412      *
413      * @return void
414      */
415     function getInstructions()
416     {
417         // TRANS: Form instructions.
418         return _('Authorize access to your account information.');
419     }
420
421     /**
422      * A local menu
423      *
424      * Shows different login/register actions.
425      *
426      * @return void
427      */
428     function showLocalNav()
429     {
430         // NOP
431     }
432
433     /*
434      * Checks to see if a the "mode" parameter is present in the request
435      * and set to "desktop". If it is, the page is meant to be displayed in
436      * a small frame of another application, and we should  suppress the
437      * header, aside, and footer.
438      */
439     function desktopMode()
440     {
441         if (isset($this->mode) && $this->mode == 'desktop') {
442             return true;
443         } else {
444             return false;
445         }
446     }
447
448     /*
449      * Override - suppress output in "desktop" mode
450      */
451     function showHeader()
452     {
453         if ($this->desktopMode() == false) {
454             parent::showHeader();
455         }
456     }
457
458     /*
459      * Override - suppress output in "desktop" mode
460      */
461     function showAside()
462     {
463         if ($this->desktopMode() == false) {
464             parent::showAside();
465         }
466     }
467
468     /*
469      * Override - suppress output in "desktop" mode
470      */
471     function showFooter()
472     {
473         if ($this->desktopMode() == false) {
474             parent::showFooter();
475         }
476     }
477
478     /**
479      * Show site notice.
480      *
481      * @return nothing
482      */
483     function showSiteNotice()
484     {
485         // NOP
486     }
487
488     /**
489      * Show notice form.
490      *
491      * Show the form for posting a new notice
492      *
493      * @return nothing
494      */
495     function showNoticeForm()
496     {
497         // NOP
498     }
499
500     /*
501      * Show a nice message confirming the authorization
502      * operation was canceled.
503      *
504      * @return nothing
505      */
506     function showCanceled()
507     {
508         $info = new InfoAction(
509             // TRANS: Header for user notification after revoking OAuth access to an application.
510             _('Authorization canceled.'),
511             sprintf(
512                 // TRANS: User notification after revoking OAuth access to an application.
513                 // TRANS: %s is an OAuth token.
514                 _('The request token %s has been revoked.'),
515                 $this->oauthTokenParm
516             )
517         );
518
519         $info->showPage();
520     }
521
522     /*
523      * Show a nice message that the authorization was successful.
524      * If the operation is out-of-band, show a pin.
525      *
526      * @return nothing
527      */
528     function showAuthorized()
529     {
530         $title = sprintf(
531            // TRANS: Header of user notification after authorising an application access to a profile.
532            // TRANS: %s is the authorised application name.
533             _("You have successfully authorized %s."),
534             $this->app->name
535         );
536
537         $msg = sprintf(
538             // TRANS: Uer notification after authorising an application access to a profile.
539             // TRANS: %s is the authorised application name.
540             _('Please return to %s and enter the following security code to complete the process.'),
541             $this->app->name
542         );
543
544         if ($this->reqToken->verified_callback == 'oob') {
545             $pin = new ApiOauthPinAction($title, $msg, $this->reqToken->verifier);
546             $pin->showPage();
547         } else {
548
549             // NOTE: This would only happen if an application registered as
550             // a web application but sent in 'oob' for the oauth_callback
551             // parameter. Usually web apps will send in a callback and
552             // not use the pin-based workflow.
553
554             $info = new InfoAction(
555                 $title,
556                 $msg,
557                 $this->oauthTokenParam,
558                 $this->reqToken->verifier
559             );
560
561             $info->showPage();
562         }
563     }
564
565     /*
566      * Properly format the callback URL and parameters so it's
567      * suitable for a redirect in the OAuth dance
568      *
569      * @param string $url       the URL
570      * @param array  $params    an array of parameters
571      *
572      * @return string $url  a URL to use for redirecting to
573      */
574     function getCallback($url, $params)
575     {
576         foreach ($params as $k => $v) {
577             $url = $this->appendQueryVar(
578                 $url,
579                 OAuthUtil::urlencode_rfc3986($k),
580                 OAuthUtil::urlencode_rfc3986($v)
581             );
582         }
583
584         return $url;
585     }
586
587     /*
588      * Append a new query parameter after any existing query
589      * parameters.
590      *
591      * @param string $url   the URL
592      * @prarm string $k     the parameter name
593      * @param string $v     value of the paramter
594      *
595      * @return string $url  the new URL with added parameter
596      */
597     function appendQueryVar($url, $k, $v) {
598         $url = preg_replace('/(.*)(\?|&)' . $k . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
599         $url = substr($url, 0, -1);
600         if (strpos($url, '?') === false) {
601             return ($url . '?' . $k . '=' . $v);
602         } else {
603             return ($url . '&' . $k . '=' . $v);
604         }
605     }
606 }