]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apioauthauthorize.php
Merge branch '0.9.x' into 1.0.x
[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         // fetch the token
176         $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
177         assert(!empty($this->reqToken));
178
179         if ($this->arg('allow')) {
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                     "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
254         } else if ($this->arg('cancel')) {
255
256             common_log(
257                 LOG_INFO,
258                 sprintf(
259                     "API OAuth - User %d (%s) refused to authorize request token %s for OAuth application %d (%s).",
260                     $user->id,
261                     $user->nickname,
262                     $this->reqToken->tok,
263                     $this->app->id,
264                     $this->app->name
265                 )
266             );
267
268             try {
269                 $this->store->revoke_token($this->oauthTokenParam, 0);
270             } catch (Exception $e) {
271                 $this->ServerError($e->getMessage());
272             }
273
274             $callback = $this->getCallback();
275
276             // If there's a callback available, inform the consumer the user
277             // has refused authorization
278             if (!empty($callback) && $this->reqToken->verified_callback != 'oob') {
279                 $targetUrl = $this->buildCallbackUrl(
280                     $callback,
281                     array(
282                         'oauth_problem' => 'user_refused',
283                     )
284                 );
285
286                 common_log(LOG_INFO, "Redirecting to callback: $targetUrl");
287
288                 // Redirect the user to the provided OAuth callback
289                 common_redirect($targetUrl, 303);
290             }
291
292             // otherwise inform the user that authorization for the rt was declined
293             $this->showCanceled();
294
295         } else {
296             // TRANS: Client error given on when invalid data was passed through a form in the OAuth API.
297             $this->clientError(_('Unexpected form submission.'));
298         }
299     }
300
301     // XXX Remove this function when we hit 1.0
302     function ensureOauthTokenAssociationTable()
303     {
304         $schema = Schema::get();
305
306         $reqTokenCols = array(
307             new ColumnDef('profile_id', 'integer', null, true, 'PRI'),
308             new ColumnDef('application_id', 'integer', null, true, 'PRI'),
309             new ColumnDef('token', 'varchar', 255, true, 'PRI'),
310             new ColumnDef('created', 'datetime', null, false),
311             new ColumnDef(
312                 'modified',
313                 'timestamp',
314                 null,
315                 false,
316                 null,
317                 'CURRENT_TIMESTAMP',
318                 'on update CURRENT_TIMESTAMP'
319             )
320         );
321
322         $schema->ensureTable('oauth_token_association', $reqTokenCols);
323     }
324
325     /**
326      * Show body - override to add a special CSS class for the authorize
327      * page's "desktop mode" (minimal display)
328      *
329      * Calls template methods
330      *
331      * @return nothing
332      */
333     function showBody()
334     {
335         $bodyClasses = array();
336
337         if ($this->desktopMode()) {
338             $bodyClasses[] = 'oauth-desktop-mode';
339         }
340
341         if (common_current_user()) {
342             $bodyClasses[] = 'user_in';
343         }
344
345         $attrs = array('id' => strtolower($this->trimmed('action')));
346
347         if (!empty($bodyClasses)) {
348             $attrs['class'] = implode(' ', $bodyClasses);
349         }
350
351         $this->elementStart('body', $attrs);
352
353         $this->elementStart('div', array('id' => 'wrap'));
354         if (Event::handle('StartShowHeader', array($this))) {
355             $this->showHeader();
356             Event::handle('EndShowHeader', array($this));
357         }
358         $this->showCore();
359         if (Event::handle('StartShowFooter', array($this))) {
360             $this->showFooter();
361             Event::handle('EndShowFooter', array($this));
362         }
363         $this->elementEnd('div');
364         $this->showScripts();
365         $this->elementEnd('body');
366     }
367
368     function showForm($error=null)
369     {
370         $this->error = $error;
371         $this->showPage();
372     }
373
374     function showScripts()
375     {
376         parent::showScripts();
377         if (!common_logged_in()) {
378             $this->autofocus('nickname');
379         }
380     }
381
382     /**
383      * Title of the page
384      *
385      * @return string title of the page
386      */
387     function title()
388     {
389         // TRANS: Title for a page where a user can confirm/deny account access by an external application.
390         return _('An application would like to connect to your account');
391     }
392
393     /**
394      * Shows the authorization form.
395      *
396      * @return void
397      */
398     function showContent()
399     {
400         $this->elementStart('form', array('method' => 'post',
401                                           'id' => 'form_apioauthauthorize',
402                                           'class' => 'form_settings',
403                                           'action' => common_local_url('ApiOauthAuthorize')));
404         $this->elementStart('fieldset');
405         $this->element('legend', array('id' => 'apioauthauthorize_allowdeny'),
406                                  // TRANS: Fieldset legend.
407                                  _('Allow or deny access'));
408
409         $this->hidden('token', common_session_token());
410         $this->hidden('mode', $this->mode);
411         $this->hidden('oauth_token', $this->oauthTokenParam);
412         $this->hidden('oauth_callback', $this->callback);
413
414         $this->elementStart('ul', 'form_data');
415         $this->elementStart('li');
416         $this->elementStart('p');
417         if (!empty($this->app->icon) && $this->app->name != 'anonymous') {
418             $this->element('img', array('src' => $this->app->icon));
419         }
420
421         $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
422           'access and update' : 'access';
423
424         // TRANS: User notification of external application requesting account access.
425         // TRANS: %1$s is the application name requesting access, %2$s is the organisation behind the application,
426         // TRANS: %3$s is the access type requested, %4$s is the StatusNet sitename.
427         if ($this->app->name == 'anonymous') {
428         // Special message for the anonymous app and consumer
429             $msg = _('An application would like the ability ' .
430                  'to <strong>%3$s</strong> your %4$s account data. ' .
431                  'You should only give access to your %4$s account ' .
432                  'to third parties you trust.');
433         } else {
434             $msg = _('The application <strong>%1$s</strong> by ' .
435                      '<strong>%2$s</strong> would like the ability ' .
436                      'to <strong>%3$s</strong> your %4$s account data. ' .
437                      'You should only give access to your %4$s account ' .
438                      'to third parties you trust.');
439         }
440
441         $this->raw(sprintf($msg,
442                            $this->app->name,
443                            $this->app->organization,
444                            $access,
445                            common_config('site', 'name')));
446         $this->elementEnd('p');
447         $this->elementEnd('li');
448         $this->elementEnd('ul');
449
450         // quickie hack
451         $button = false;
452         if (!common_logged_in()) {
453             if (Event::handle('StartOAuthLoginForm', array($this, &$button))) {
454                 $this->elementStart('fieldset');
455                 // TRANS: Fieldset legend.
456                 $this->element('legend', null, _m('LEGEND','Account'));
457                 $this->elementStart('ul', 'form_data');
458                 $this->elementStart('li');
459                 // TRANS: Field label on OAuth API authorisation form.
460                 $this->input('nickname', _('Nickname'));
461                 $this->elementEnd('li');
462                 $this->elementStart('li');
463                 // TRANS: Field label on OAuth API authorisation form.
464                 $this->password('password', _('Password'));
465                 $this->elementEnd('li');
466                 $this->elementEnd('ul');
467
468                 $this->elementEnd('fieldset');
469             }
470             Event::handle('EndOAuthLoginForm', array($this, &$button));
471         }
472
473         $this->element('input', array('id' => 'cancel_submit',
474                                       'class' => 'submit submit form_action-primary',
475                                       'name' => 'cancel',
476                                       'type' => 'submit',
477                                       // TRANS: Button text that when clicked will cancel the process of allowing access to an account
478                                       // TRANS: by an external application.
479                                       'value' => _m('BUTTON','Cancel')));
480
481         $this->element('input', array('id' => 'allow_submit',
482                                       'class' => 'submit submit form_action-secondary',
483                                       'name' => 'allow',
484                                       'type' => 'submit',
485                                       // TRANS: Button text that when clicked will allow access to an account by an external application.
486                                       'value' => $button ? $button : _m('BUTTON','Allow')));
487
488         $this->elementEnd('fieldset');
489         $this->elementEnd('form');
490     }
491
492     /**
493      * Instructions for using the form
494      *
495      * For "remembered" logins, we make the user re-login when they
496      * try to change settings. Different instructions for this case.
497      *
498      * @return void
499      */
500     function getInstructions()
501     {
502         // TRANS: Form instructions.
503         return _('Authorize access to your account information.');
504     }
505
506     /**
507      * A local menu
508      *
509      * Shows different login/register actions.
510      *
511      * @return void
512      */
513     function showLocalNav()
514     {
515         // NOP
516     }
517
518     /*
519      * Checks to see if a the "mode" parameter is present in the request
520      * and set to "desktop". If it is, the page is meant to be displayed in
521      * a small frame of another application, and we should  suppress the
522      * header, aside, and footer.
523      */
524     function desktopMode()
525     {
526         if (isset($this->mode) && $this->mode == 'desktop') {
527             return true;
528         } else {
529             return false;
530         }
531     }
532
533     /*
534      * Override - suppress output in "desktop" mode
535      */
536     function showHeader()
537     {
538         if ($this->desktopMode() == false) {
539             parent::showHeader();
540         }
541     }
542
543     /*
544      * Override - suppress output in "desktop" mode
545      */
546     function showAside()
547     {
548         if ($this->desktopMode() == false) {
549             parent::showAside();
550         }
551     }
552
553     /*
554      * Override - suppress output in "desktop" mode
555      */
556     function showFooter()
557     {
558         if ($this->desktopMode() == false) {
559             parent::showFooter();
560         }
561     }
562
563     /**
564      * Show site notice.
565      *
566      * @return nothing
567      */
568     function showSiteNotice()
569     {
570         // NOP
571     }
572
573     /**
574      * Show notice form.
575      *
576      * Show the form for posting a new notice
577      *
578      * @return nothing
579      */
580     function showNoticeForm()
581     {
582         // NOP
583     }
584
585     /*
586      * Show a nice message confirming the authorization
587      * operation was canceled.
588      *
589      * @return nothing
590      */
591     function showCanceled()
592     {
593         $info = new InfoAction(
594             // TRANS: Header for user notification after revoking OAuth access to an application.
595             _('Authorization canceled.'),
596             sprintf(
597                 // TRANS: User notification after revoking OAuth access to an application.
598                 // TRANS: %s is an OAuth token.
599                 _('The request token %s has been revoked.'),
600                 $this->oauthTokenParam
601             )
602         );
603
604         $info->showPage();
605     }
606
607     /*
608      * Show a nice message that the authorization was successful.
609      * If the operation is out-of-band, show a pin.
610      *
611      * @return nothing
612      */
613     function showAuthorized()
614     {
615         $title = sprintf(
616            // TRANS: Header of user notification after authorising an application access to a profile.
617            // TRANS: %s is the authorised application name.
618             _('You have successfully authorized %s.'),
619             ($this->app->name == 'anonymous') ? 'the application' : $this->app->name
620         );
621
622         $msg = sprintf(
623             // TRANS: Uer notification after authorising an application access to a profile.
624             // TRANS: %s is the authorised application name.
625             _('Please return to %s and enter the following security code to complete the process.'),
626             ($this->app->name == 'anonymous') ? 'the application' : $this->app->name
627         );
628
629         if ($this->reqToken->verified_callback == 'oob') {
630             $pin = new ApiOauthPinAction(
631                 $title,
632                 $msg,
633                 $this->reqToken->verifier,
634                 $this->desktopMode()
635             );
636             $pin->showPage();
637         } else {
638
639             // NOTE: This would only happen if an application registered as
640             // a web application but sent in 'oob' for the oauth_callback
641             // parameter. Usually web apps will send in a callback and
642             // not use the pin-based workflow.
643
644             $info = new InfoAction(
645                 $title,
646                 $msg,
647                 $this->oauthTokenParam,
648                 $this->reqToken->verifier
649             );
650
651             $info->showPage();
652         }
653     }
654
655     /*
656      * Figure out what the callback should be
657      */
658     function getCallback()
659     {
660         $callback = null;
661
662         // Return the verified callback if we have one
663         if ($this->reqToken->verified_callback != 'oob') {
664
665             $callback = $this->reqToken->verified_callback;
666
667             // Otherwise return the callback that was provided when
668             // registering the app
669             if (empty($callback)) {
670
671                 common_debug(
672                     "No verified callback found for request token, using application callback: "
673                         . $this->app->callback_url,
674                      __FILE__
675                 );
676
677                 $callback = $this->app->callback_url;
678             }
679
680         }
681
682         return $callback;
683     }
684
685     /*
686      * Properly format the callback URL and parameters so it's
687      * suitable for a redirect in the OAuth dance
688      *
689      * @param string $url       the URL
690      * @param array  $params    an array of parameters
691      *
692      * @return string $url  a URL to use for redirecting to
693      */
694     function buildCallbackUrl($url, $params)
695     {
696         foreach ($params as $k => $v) {
697             $url = $this->appendQueryVar(
698                 $url,
699                 OAuthUtil::urlencode_rfc3986($k),
700                 OAuthUtil::urlencode_rfc3986($v)
701             );
702         }
703
704         return $url;
705     }
706
707     /*
708      * Append a new query parameter after any existing query
709      * parameters.
710      *
711      * @param string $url   the URL
712      * @prarm string $k     the parameter name
713      * @param string $v     value of the paramter
714      *
715      * @return string $url  the new URL with added parameter
716      */
717     function appendQueryVar($url, $k, $v) {
718         $url = preg_replace('/(.*)(\?|&)' . $k . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
719         $url = substr($url, 0, -1);
720         if (strpos($url, '?') === false) {
721             return ($url . '?' . $k . '=' . $v);
722         } else {
723             return ($url . '&' . $k . '=' . $v);
724         }
725     }
726 }