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