]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apioauthauthorize.php
Add support for an anonymous OAuth consumer. Note: this requires a
[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
47 class ApiOauthAuthorizeAction extends Action
48 {
49     var $oauthTokenParam;
50     var $reqToken;
51     var $callback;
52     var $app;
53     var $nickname;
54     var $password;
55     var $store;
56
57     /**
58      * Is this a read-only action?
59      *
60      * @return boolean false
61      */
62
63     function isReadOnly($args)
64     {
65         return false;
66     }
67
68     function prepare($args)
69     {
70         parent::prepare($args);
71
72         $this->nickname         = $this->trimmed('nickname');
73         $this->password         = $this->arg('password');
74         $this->oauthTokenParam  = $this->arg('oauth_token');
75         $this->callback         = $this->arg('oauth_callback');
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
97     function handle($args)
98     {
99         parent::handle($args);
100
101         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
102
103             $this->handlePost();
104
105         } else {
106
107             // Make sure a oauth_token parameter was provided
108             if (empty($this->oauthTokenParam)) {
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                     $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                         $this->clientError(_("Invalid request token."));
122                     }
123                 }
124             }
125
126             // make sure there's an app associated with this token
127             if (empty($this->app)) {
128                 $this->clientError(_('Invalid request token.'));
129             }
130
131             $name = $this->app->name;
132
133             $this->showForm();
134         }
135     }
136
137     function handlePost()
138     {
139         // check session token for CSRF protection.
140
141         $token = $this->trimmed('token');
142
143         if (!$token || $token != common_session_token()) {
144             $this->showForm(
145                 _('There was a problem with your session token. Try again, please.'));
146             return;
147         }
148
149         // check creds
150
151         $user = null;
152
153         if (!common_logged_in()) {
154
155             // XXX Force credentials check?
156
157             // XXX OpenID
158
159             $user = common_check_user($this->nickname, $this->password);
160             if (empty($user)) {
161                 $this->showForm(_("Invalid nickname / password!"));
162                 return;
163             }
164         } else {
165             $user = common_current_user();
166         }
167
168         if ($this->arg('allow')) {
169
170             // fetch the token
171             $this->reqToken = $this->store->getTokenByKey($this->oauthTokenParam);
172
173             // mark the req token as authorized
174             try {
175                 $this->store->authorize_token($this->oauthTokenParam);
176             } catch (Exception $e) {
177                 $this->serverError($e->getMessage());
178             }
179
180             // associated the authorized req token with the user and the app
181
182             $appUser = new Oauth_application_user();
183
184             $appUser->profile_id     = $user->id;
185             $appUser->application_id = $this->app->id;
186
187             // Note: do not copy the access type from the application.
188             // The access type should always be 0 when the OAuth app
189             // user record has a request token associated with it.
190             // Access type gets assigned once an access token has been
191             // granted.  The OAuth app user record then gets updated
192             // with the new access token and access type.
193
194             $appUser->token          = $this->oauthTokenParam;
195             $appUser->created        = common_sql_now();
196
197             $result = $appUser->insert();
198
199             if (!$result) {
200                 common_log_db_error($appUser, 'INSERT', __FILE__);
201                 $this->serverError(_('Database error inserting OAuth application user.'));
202             }
203
204             // If we have a callback redirect and provide the token
205
206             // Note: A callback specified in the app setup overrides whatever
207             // is passed in with the request.
208
209             if (!empty($this->app->callback_url)) {
210                 $this->callback = $this->app->callback_url;
211             }
212
213             if (!empty($this->callback)) {
214
215                 $targetUrl = $this->getCallback(
216                     $this->callback,
217                     array(
218                         'oauth_token'    => $this->oauthTokenParam,
219                         'oauth_verifier' => $this->reqToken->verifier // 1.0a
220                     )
221                 );
222
223                 // Redirect the user to the provided OAuth callback
224                 common_redirect($targetUrl, 303);
225
226             } elseif ($this->app->type == 2) {
227
228                 // Strangely, a web application seems to want to do the OOB
229                 // workflow. Because no callback was specified anywhere.
230                 common_log(
231                     LOG_WARNING,
232                     sprintf(
233                         "API OAuth - No callback provided for OAuth web client ID %s (%s) "
234                          . "during authorization step. Falling back to OOB workflow.",
235                         $this->app->id,
236                         $this->app->name
237                     )
238                 );
239             }
240
241             common_log(
242                 LOG_INFO,
243                 sprintf(
244                     "The request token '%s' for OAuth application %s (%s) has been authorized.",
245                     $this->oauthTokenParam,
246                     $this->app->id,
247                     $this->app->name
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             try {
257                 $this->store->revoke_token($this->oauthTokenParam, 0);
258                 $this->showCanceled();
259             } catch (Exception $e) {
260                 $this->ServerError($e->getMessage());
261             }
262
263         } else {
264             $this->clientError(_('Unexpected form submission.'));
265         }
266     }
267
268     function showForm($error=null)
269     {
270         $this->error = $error;
271         $this->showPage();
272     }
273
274     function showScripts()
275     {
276         parent::showScripts();
277         if (!common_logged_in()) {
278             $this->autofocus('nickname');
279         }
280     }
281
282     /**
283      * Title of the page
284      *
285      * @return string title of the page
286      */
287
288     function title()
289     {
290         return _('An application would like to connect to your account');
291     }
292
293     /**
294      * Shows the authorization form.
295      *
296      * @return void
297      */
298
299     function showContent()
300     {
301         $this->elementStart('form', array('method' => 'post',
302                                           'id' => 'form_apioauthauthorize',
303                                           'class' => 'form_settings',
304                                           'action' => common_local_url('ApiOauthAuthorize')));
305         $this->elementStart('fieldset');
306         $this->element('legend', array('id' => 'apioauthauthorize_allowdeny'),
307                                  _('Allow or deny access'));
308
309         $this->hidden('token', common_session_token());
310         $this->hidden('oauth_token', $this->oauthTokenParam);
311         $this->hidden('oauth_callback', $this->callback);
312
313         $this->elementStart('ul', 'form_data');
314         $this->elementStart('li');
315         $this->elementStart('p');
316         if (!empty($this->app->icon)) {
317             $this->element('img', array('src' => $this->app->icon));
318         }
319
320         $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
321           'access and update' : 'access';
322
323         $msg = _('The application <strong>%1$s</strong> by ' .
324                  '<strong>%2$s</strong> would like the ability ' .
325                  'to <strong>%3$s</strong> your %4$s account data. ' .
326                  'You should only give access to your %4$s account ' .
327                  'to third parties you trust.');
328
329         $this->raw(sprintf($msg,
330                            $this->app->name,
331                            $this->app->organization,
332                            $access,
333                            common_config('site', 'name')));
334         $this->elementEnd('p');
335         $this->elementEnd('li');
336         $this->elementEnd('ul');
337
338         if (!common_logged_in()) {
339
340             $this->elementStart('fieldset');
341             $this->element('legend', null, _('Account'));
342             $this->elementStart('ul', 'form_data');
343             $this->elementStart('li');
344             $this->input('nickname', _('Nickname'));
345             $this->elementEnd('li');
346             $this->elementStart('li');
347             $this->password('password', _('Password'));
348             $this->elementEnd('li');
349             $this->elementEnd('ul');
350
351             $this->elementEnd('fieldset');
352
353         }
354
355         $this->element('input', array('id' => 'cancel_submit',
356                                       'class' => 'submit submit form_action-primary',
357                                       'name' => 'cancel',
358                                       'type' => 'submit',
359                                       'value' => _('Cancel')));
360
361         $this->element('input', array('id' => 'allow_submit',
362                                       'class' => 'submit submit form_action-secondary',
363                                       'name' => 'allow',
364                                       'type' => 'submit',
365                                       'value' => _('Allow')));
366
367         $this->elementEnd('fieldset');
368         $this->elementEnd('form');
369     }
370
371     /**
372      * Instructions for using the form
373      *
374      * For "remembered" logins, we make the user re-login when they
375      * try to change settings. Different instructions for this case.
376      *
377      * @return void
378      */
379
380     function getInstructions()
381     {
382         return _('Authorize access to your account information.');
383     }
384
385     /**
386      * A local menu
387      *
388      * Shows different login/register actions.
389      *
390      * @return void
391      */
392
393     function showLocalNav()
394     {
395         // NOP
396     }
397
398     /**
399      * Show site notice.
400      *
401      * @return nothing
402      */
403
404     function showSiteNotice()
405     {
406         // NOP
407     }
408
409     /**
410      * Show notice form.
411      *
412      * Show the form for posting a new notice
413      *
414      * @return nothing
415      */
416
417     function showNoticeForm()
418     {
419         // NOP
420     }
421
422     /*
423      * Show a nice message confirming the authorization
424      * operation was canceled.
425      *
426      * @return nothing
427      */
428
429     function showCanceled()
430     {
431         $info = new InfoAction(
432             _('Authorization canceled.'),
433             sprintf(
434                 _('The request token %s has been revoked.'),
435                 $this->oauthTokenParm
436             )
437         );
438
439         $info->showPage();
440     }
441
442     /*
443      * Show a nice message that the authorization was successful.
444      * If the operation is out-of-band, show a pin.
445      *
446      * @return nothing
447      */
448
449     function showAuthorized()
450     {
451         $title = sprintf(
452             _("You have successfully authorized %s."),
453             $this->app->name
454         );
455
456         $msg = sprintf(
457             _('Please return to %s and enter the following security code to complete the process.'),
458             $this->app->name
459         );
460
461         if ($this->reqToken->verified_callback == 'oob') {
462             $pin = new ApiOauthPinAction($title, $msg, $this->reqToken->verifier);
463             $pin->showPage();
464         } else {
465
466             // NOTE: This would only happen if an application registered as
467             // a web application but sent in 'oob' for the oauth_callback
468             // parameter. Usually web apps will send in a callback and
469             // not use the pin-based workflow.
470
471             $info = new InfoAction(
472                 $title,
473                 $msg,
474                 $this->oauthTokenParam,
475                 $this->reqToken->verifier
476             );
477
478             $info->showPage();
479         }
480     }
481
482     /*
483      * Properly format the callback URL and parameters so it's
484      * suitable for a redirect in the OAuth dance
485      *
486      * @param string $url       the URL
487      * @param array  $params    an array of parameters
488      *
489      * @return string $url  a URL to use for redirecting to
490      */
491
492     function getCallback($url, $params)
493     {
494         foreach ($params as $k => $v) {
495             $url = $this->appendQueryVar(
496                 $url,
497                 OAuthUtil::urlencode_rfc3986($k),
498                 OAuthUtil::urlencode_rfc3986($v)
499             );
500         }
501
502         return $url;
503     }
504
505     /*
506      * Append a new query parameter after any existing query
507      * parameters.
508      *
509      * @param string $url   the URL
510      * @prarm string $k     the parameter name
511      * @param string $v     value of the paramter
512      *
513      * @return string $url  the new URL with added parameter
514      */
515
516     function appendQueryVar($url, $k, $v) {
517         $url = preg_replace('/(.*)(\?|&)' . $k . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
518         $url = substr($url, 0, -1);
519         if (strpos($url, '?') === false) {
520             return ($url . '?' . $k . '=' . $v);
521         } else {
522             return ($url . '&' . $k . '=' . $v);
523         }
524     }
525 }