]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apioauthauthorize.php
Merge branch '0.9.x' of gitorious.org:statusnet/mainline into 0.9.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 OAuth 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->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
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(_("Invalid request token."));
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             // associated the authorized req token with the user and the app
189
190             $appUser = new Oauth_application_user();
191
192             $appUser->profile_id     = $user->id;
193             $appUser->application_id = $this->app->id;
194
195             // Note: do not copy the access type from the application.
196             // The access type should always be 0 when the OAuth app
197             // user record has a request token associated with it.
198             // Access type gets assigned once an access token has been
199             // granted.  The OAuth app user record then gets updated
200             // with the new access token and access type.
201
202             $appUser->token          = $this->oauthTokenParam;
203             $appUser->created        = common_sql_now();
204
205             $result = $appUser->insert();
206
207             if (!$result) {
208                 common_log_db_error($appUser, 'INSERT', __FILE__);
209                 // TRANS: Server error given when a database error occurs inserting an OAuth application user.
210                 $this->serverError(_('Database error inserting OAuth application user.'));
211             }
212
213             // If we have a callback redirect and provide the token
214
215             // Note: A callback specified in the app setup overrides whatever
216             // is passed in with the request.
217
218             if (!empty($this->app->callback_url)) {
219                 $this->callback = $this->app->callback_url;
220             }
221
222             if (!empty($this->callback)) {
223                 $targetUrl = $this->getCallback(
224                     $this->callback,
225                     array(
226                         'oauth_token'    => $this->oauthTokenParam,
227                         'oauth_verifier' => $this->reqToken->verifier // 1.0a
228                     )
229                 );
230
231                 // Redirect the user to the provided OAuth callback
232                 common_redirect($targetUrl, 303);
233             } elseif ($this->app->type == 2) {
234                 // Strangely, a web application seems to want to do the OOB
235                 // workflow. Because no callback was specified anywhere.
236                 common_log(
237                     LOG_WARNING,
238                     sprintf(
239                         "API OAuth - No callback provided for OAuth web client ID %s (%s) "
240                          . "during authorization step. Falling back to OOB workflow.",
241                         $this->app->id,
242                         $this->app->name
243                     )
244                 );
245             }
246
247             common_log(
248                 LOG_INFO,
249                 sprintf(
250                     "The request token '%s' for OAuth application %s (%s) has been authorized.",
251                     $this->oauthTokenParam,
252                     $this->app->id,
253                     $this->app->name
254                 )
255             );
256
257             // Otherwise, inform the user that the rt was authorized
258             $this->showAuthorized();
259
260         } else if ($this->arg('cancel')) {
261
262             try {
263                 $this->store->revoke_token($this->oauthTokenParam, 0);
264                 $this->showCanceled();
265             } catch (Exception $e) {
266                 $this->ServerError($e->getMessage());
267             }
268
269         } else {
270             // TRANS: Client error given on when invalid data was passed through a form in the OAuth API.
271             $this->clientError(_('Unexpected form submission.'));
272         }
273     }
274
275     function showForm($error=null)
276     {
277         $this->error = $error;
278         $this->showPage();
279     }
280
281     function showScripts()
282     {
283         parent::showScripts();
284         if (!common_logged_in()) {
285             $this->autofocus('nickname');
286         }
287     }
288
289     /**
290      * Title of the page
291      *
292      * @return string title of the page
293      */
294
295     function title()
296     {
297         // TRANS: Title for a page where a user can confirm/deny account access by an external application.
298         return _('An application would like to connect to your account');
299     }
300
301     /**
302      * Shows the authorization form.
303      *
304      * @return void
305      */
306
307     function showContent()
308     {
309         $this->elementStart('form', array('method' => 'post',
310                                           'id' => 'form_apioauthauthorize',
311                                           'class' => 'form_settings',
312                                           'action' => common_local_url('ApiOauthAuthorize')));
313         $this->elementStart('fieldset');
314         $this->element('legend', array('id' => 'apioauthauthorize_allowdeny'),
315                                  // TRANS: Fieldset legend.
316                                  _('Allow or deny access'));
317
318         $this->hidden('token', common_session_token());
319         $this->hidden('oauth_token', $this->oauthTokenParam);
320         $this->hidden('oauth_callback', $this->callback);
321
322         $this->elementStart('ul', 'form_data');
323         $this->elementStart('li');
324         $this->elementStart('p');
325         if (!empty($this->app->icon)) {
326             $this->element('img', array('src' => $this->app->icon));
327         }
328
329         $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
330           'access and update' : 'access';
331
332         // TRANS: User notification of external application requesting account access.
333         // TRANS: %1$s is the application name requesting access, %2$s is the organisation behind the application,
334         // TRANS: %3$s is the access type requested, %4$s is the StatusNet sitename.
335         $msg = _('The application <strong>%1$s</strong> by ' .
336                  '<strong>%2$s</strong> would like the ability ' .
337                  'to <strong>%3$s</strong> your %4$s account data. ' .
338                  'You should only give access to your %4$s account ' .
339                  'to third parties you trust.');
340
341         $this->raw(sprintf($msg,
342                            $this->app->name,
343                            $this->app->organization,
344                            $access,
345                            common_config('site', 'name')));
346         $this->elementEnd('p');
347         $this->elementEnd('li');
348         $this->elementEnd('ul');
349
350         // quickie hack
351         $button = false;
352         if (!common_logged_in()) {
353             if (Event::handle('StartOAuthLoginForm', array($this, &$button))) {
354                 $this->elementStart('fieldset');
355                 // TRANS: Fieldset legend.
356                 $this->element('legend', null, _m('LEGEND','Account'));
357                 $this->elementStart('ul', 'form_data');
358                 $this->elementStart('li');
359                 // TRANS: Field label on OAuth API authorisation form.
360                 $this->input('nickname', _('Nickname'));
361                 $this->elementEnd('li');
362                 $this->elementStart('li');
363                 // TRANS: Field label on OAuth API authorisation form.
364                 $this->password('password', _('Password'));
365                 $this->elementEnd('li');
366                 $this->elementEnd('ul');
367
368                 $this->elementEnd('fieldset');
369             }
370             Event::handle('EndOAuthLoginForm', array($this, &$button));
371         }
372
373         $this->element('input', array('id' => 'cancel_submit',
374                                       'class' => 'submit submit form_action-primary',
375                                       'name' => 'cancel',
376                                       'type' => 'submit',
377                                       // TRANS: Button text that when clicked will cancel the process of allowing access to an account
378                                       // TRANS: by an external application.
379                                       'value' => _m('BUTTON','Cancel')));
380
381         $this->element('input', array('id' => 'allow_submit',
382                                       'class' => 'submit submit form_action-secondary',
383                                       'name' => 'allow',
384                                       'type' => 'submit',
385                                       // TRANS: Button text that when clicked will allow access to an account by an external application.
386                                       'value' => $button ? $button : _m('BUTTON','Allow')));
387
388         $this->elementEnd('fieldset');
389         $this->elementEnd('form');
390     }
391
392     /**
393      * Instructions for using the form
394      *
395      * For "remembered" logins, we make the user re-login when they
396      * try to change settings. Different instructions for this case.
397      *
398      * @return void
399      */
400     function getInstructions()
401     {
402         // TRANS: Form instructions.
403         return _('Authorize access to your account information.');
404     }
405
406     /**
407      * A local menu
408      *
409      * Shows different login/register actions.
410      *
411      * @return void
412      */
413     function showLocalNav()
414     {
415         // NOP
416     }
417
418     /**
419      * Show site notice.
420      *
421      * @return nothing
422      */
423     function showSiteNotice()
424     {
425         // NOP
426     }
427
428     /**
429      * Show notice form.
430      *
431      * Show the form for posting a new notice
432      *
433      * @return nothing
434      */
435     function showNoticeForm()
436     {
437         // NOP
438     }
439
440     /*
441      * Show a nice message confirming the authorization
442      * operation was canceled.
443      *
444      * @return nothing
445      */
446     function showCanceled()
447     {
448         $info = new InfoAction(
449             // TRANS: Header for user notification after revoking OAuth access to an application.
450             _('Authorization canceled.'),
451             sprintf(
452                 // TRANS: User notification after revoking OAuth access to an application.
453                 // TRANS: %s is an OAuth token.
454                 _('The request token %s has been revoked.'),
455                 $this->oauthTokenParm
456             )
457         );
458
459         $info->showPage();
460     }
461
462     /*
463      * Show a nice message that the authorization was successful.
464      * If the operation is out-of-band, show a pin.
465      *
466      * @return nothing
467      */
468     function showAuthorized()
469     {
470         $title = sprintf(
471            // TRANS: Header of user notification after authorising an application access to a profile.
472            // TRANS: %s is the authorised application name.
473             _("You have successfully authorized %s."),
474             $this->app->name
475         );
476
477         $msg = sprintf(
478             // TRANS: Uer notification after authorising an application access to a profile.
479             // TRANS: %s is the authorised application name.
480             _('Please return to %s and enter the following security code to complete the process.'),
481             $this->app->name
482         );
483
484         if ($this->reqToken->verified_callback == 'oob') {
485             $pin = new ApiOauthPinAction($title, $msg, $this->reqToken->verifier);
486             $pin->showPage();
487         } else {
488
489             // NOTE: This would only happen if an application registered as
490             // a web application but sent in 'oob' for the oauth_callback
491             // parameter. Usually web apps will send in a callback and
492             // not use the pin-based workflow.
493
494             $info = new InfoAction(
495                 $title,
496                 $msg,
497                 $this->oauthTokenParam,
498                 $this->reqToken->verifier
499             );
500
501             $info->showPage();
502         }
503     }
504
505     /*
506      * Properly format the callback URL and parameters so it's
507      * suitable for a redirect in the OAuth dance
508      *
509      * @param string $url       the URL
510      * @param array  $params    an array of parameters
511      *
512      * @return string $url  a URL to use for redirecting to
513      */
514     function getCallback($url, $params)
515     {
516         foreach ($params as $k => $v) {
517             $url = $this->appendQueryVar(
518                 $url,
519                 OAuthUtil::urlencode_rfc3986($k),
520                 OAuthUtil::urlencode_rfc3986($v)
521             );
522         }
523
524         return $url;
525     }
526
527     /*
528      * Append a new query parameter after any existing query
529      * parameters.
530      *
531      * @param string $url   the URL
532      * @prarm string $k     the parameter name
533      * @param string $v     value of the paramter
534      *
535      * @return string $url  the new URL with added parameter
536      */
537     function appendQueryVar($url, $k, $v) {
538         $url = preg_replace('/(.*)(\?|&)' . $k . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
539         $url = substr($url, 0, -1);
540         if (strpos($url, '?') === false) {
541             return ($url . '?' . $k . '=' . $v);
542         } else {
543             return ($url . '&' . $k . '=' . $v);
544         }
545     }
546 }