]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apioauthauthorize.php
OAuth 1.0 working now
[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
36 /**
37  * Authorize an OAuth request token
38  *
39  * @category API
40  * @package  StatusNet
41  * @author   Zach Copley <zach@status.net>
42  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
43  * @link     http://status.net/
44  */
45
46 class ApiOauthAuthorizeAction extends ApiOauthAction
47 {
48     var $oauth_token;
49     var $callback;
50     var $app;
51     var $nickname;
52     var $password;
53     var $store;
54
55     /**
56      * Is this a read-only action?
57      *
58      * @return boolean false
59      */
60
61     function isReadOnly($args)
62     {
63         return false;
64     }
65
66     function prepare($args)
67     {
68         parent::prepare($args);
69
70         common_debug("apioauthauthorize");
71
72         $this->nickname    = $this->trimmed('nickname');
73         $this->password    = $this->arg('password');
74         $this->oauth_token = $this->arg('oauth_token');
75         $this->callback    = $this->arg('oauth_callback');
76         $this->store       = new ApiStatusNetOAuthDataStore();
77
78         return true;
79     }
80
81     function getApp()
82     {
83         // Look up the full req token
84
85         $req_token = $this->store->lookup_token(null,
86                                                 'request',
87                                                 $this->oauth_token);
88
89         if (empty($req_token)) {
90
91             common_debug("Couldn't find request token!");
92
93             $this->clientError(_('Bad request.'));
94             return;
95         }
96
97         // Look up the app
98
99         $app = new Oauth_application();
100         $app->consumer_key = $req_token->consumer_key;
101         $result = $app->find(true);
102
103         if (!empty($result)) {
104             $this->app = $app;
105             return true;
106
107         } else {
108             common_debug("couldn't find the app!");
109             return false;
110         }
111     }
112
113     /**
114      * Handle input, produce output
115      *
116      * Switches on request method; either shows the form or handles its input.
117      *
118      * @param array $args $_REQUEST data
119      *
120      * @return void
121      */
122
123     function handle($args)
124     {
125         parent::handle($args);
126
127         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
128
129             $this->handlePost();
130
131         } else {
132
133             // XXX: make better error messages
134
135             if (empty($this->oauth_token)) {
136
137                 common_debug("No request token found.");
138
139                 $this->clientError(_('Bad request.'));
140                 return;
141             }
142
143             if (!$this->getApp()) {
144                 $this->clientError(_('Bad request.'));
145                 return;
146             }
147
148             $name = $this->app->name;
149             common_debug("Requesting auth for app: " . $name);
150
151             $this->showForm();
152         }
153     }
154
155     function handlePost()
156     {
157         common_debug("handlePost()");
158
159         // check session token for CSRF protection.
160
161         $token = $this->trimmed('token');
162
163         if (!$token || $token != common_session_token()) {
164             $this->showForm(_('There was a problem with your session token. '.
165                               'Try again, please.'));
166             return;
167         }
168
169         if (!$this->getApp()) {
170             $this->clientError(_('Bad request.'));
171             return;
172         }
173
174         // check creds
175
176         $user = null;
177
178         if (!common_logged_in()) {
179             $user = common_check_user($this->nickname, $this->password);
180             if (empty($user)) {
181                 $this->showForm(_("Invalid nickname / password!"));
182                 return;
183             }
184         } else {
185             $user = common_current_user();
186         }
187
188         if ($this->arg('allow')) {
189
190             // mark the req token as authorized
191
192             $this->store->authorize_token($this->oauth_token);
193
194             // Check to see if there was a previous token associated
195             // with this user/app and kill it. If the user is doing this she
196             // probably doesn't want any old tokens anyway.
197
198             $appUser = Oauth_application_user::getByKeys($user, $this->app);
199
200             if (!empty($appUser)) {
201                 $result = $appUser->delete();
202
203                 if (!$result) {
204                     common_log_db_error($appUser, 'DELETE', __FILE__);
205                     throw new ServerException(_('DB error deleting OAuth app user.'));
206                     return;
207                 }
208             }
209
210             // associated the authorized req token with the user and the app
211
212             $appUser = new Oauth_application_user();
213
214             $appUser->profile_id     = $user->id;
215             $appUser->application_id = $this->app->id;
216
217             // Note: do not copy the access type from the application.
218             // The access type should always be 0 when the OAuth app
219             // user record has a request token associated with it.
220             // Access type gets assigned once an access token has been
221             // granted.  The OAuth app user record then gets updated
222             // with the new access token and access type.
223
224             $appUser->token          = $this->oauth_token;
225             $appUser->created        = common_sql_now();
226
227             $result = $appUser->insert();
228
229             if (!$result) {
230                 common_log_db_error($appUser, 'INSERT', __FILE__);
231                 throw new ServerException(_('DB error inserting OAuth app user.'));
232                 return;
233             }
234
235             // if we have a callback redirect and provide the token
236
237             // A callback specified in the app setup overrides whatever
238             // is passed in with the request.
239
240             common_debug("Req token is authorized - doing callback");
241
242             if (!empty($this->app->callback_url)) {
243                 $this->callback = $this->app->callback_url;
244             }
245
246             if (!empty($this->callback)) {
247
248                 // XXX: Need better way to build this redirect url.
249
250                 $target_url = $this->getCallback($this->callback,
251                                                  array('oauth_token' => $this->oauth_token));
252
253                 common_debug("Doing callback to $target_url");
254
255                 common_redirect($target_url, 303);
256             } else {
257                 common_debug("callback was empty!");
258             }
259
260             // otherwise inform the user that the rt was authorized
261
262             $this->elementStart('p');
263
264             // XXX: Do OAuth 1.0a verifier code
265
266             $this->raw(sprintf(_("The request token %s has been authorized. " .
267                                  'Please exchange it for an access token.'),
268                                $this->oauth_token));
269
270             $this->elementEnd('p');
271
272         } else if ($this->arg('deny')) {
273
274             $this->elementStart('p');
275
276             $this->raw(sprintf(_("The request token %s has been denied."),
277                                $this->oauth_token));
278
279             $this->elementEnd('p');
280         } else {
281             $this->clientError(_('Unexpected form submission.'));
282             return;
283         }
284     }
285
286     function showForm($error=null)
287     {
288         $this->error = $error;
289         $this->showPage();
290     }
291
292     function showScripts()
293     {
294         parent::showScripts();
295         if (!common_logged_in()) {
296             $this->autofocus('nickname');
297         }
298     }
299
300     /**
301      * Title of the page
302      *
303      * @return string title of the page
304      */
305
306     function title()
307     {
308         return _('An application would like to connect to your account');
309     }
310
311     /**
312      * Show page notice
313      *
314      * Display a notice for how to use the page, or the
315      * error if it exists.
316      *
317      * @return void
318      */
319
320     function showPageNotice()
321     {
322         if ($this->error) {
323             $this->element('p', 'error', $this->error);
324         } else {
325             $instr  = $this->getInstructions();
326             $output = common_markup_to_html($instr);
327
328             $this->raw($output);
329         }
330     }
331
332     /**
333      * Shows the authorization form.
334      *
335      * @return void
336      */
337
338     function showContent()
339     {
340         $this->elementStart('form', array('method' => 'post',
341                                           'id' => 'form_login',
342                                           'class' => 'form_settings',
343                                           'action' => common_local_url('apioauthauthorize')));
344
345         $this->hidden('token', common_session_token());
346         $this->hidden('oauth_token', $this->oauth_token);
347         $this->hidden('oauth_callback', $this->callback);
348
349         $this->elementStart('fieldset');
350
351         $this->elementStart('ul');
352         $this->elementStart('li');
353         if (!empty($this->app->icon)) {
354             $this->element('img', array('src' => $this->app->icon));
355         }
356         $this->elementEnd('li');
357         $this->elementStart('li');
358
359         $access = ($this->app->access_type & Oauth_application::$writeAccess) ?
360           'access and update' : 'access';
361
362         $msg = _("The application <b>%s</b> by <b>%s</b> would like " .
363                  "the ability to <b>%s</b> your account data.");
364
365         $this->raw(sprintf($msg,
366                            $this->app->name,
367                            $this->app->organization,
368                            $access));
369
370         $this->elementEnd('li');
371         $this->elementEnd('ul');
372
373         $this->elementEnd('fieldset');
374
375         if (!common_logged_in()) {
376
377             $this->elementStart('fieldset');
378             $this->element('legend', null, _('Login'));
379             $this->elementStart('ul', 'form_data');
380             $this->elementStart('li');
381             $this->input('nickname', _('Nickname'));
382             $this->elementEnd('li');
383             $this->elementStart('li');
384             $this->password('password', _('Password'));
385             $this->elementEnd('li');
386             $this->elementEnd('ul');
387
388             $this->elementEnd('fieldset');
389
390         }
391
392         $this->element('input', array('id' => 'deny_submit',
393                                       'class' => 'submit',
394                                       'name' => 'deny',
395                                       'type' => 'submit',
396                                       'value' => _('Deny')));
397
398         $this->element('input', array('id' => 'allow_submit',
399                                       'class' => 'submit',
400                                       'name' => 'allow',
401                                       'type' => 'submit',
402                                       'value' => _('Allow')));
403
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
416     function getInstructions()
417     {
418         return _('Allow or deny access to your account information.');
419
420     }
421
422     /**
423      * A local menu
424      *
425      * Shows different login/register actions.
426      *
427      * @return void
428      */
429
430     function showLocalNav()
431     {
432     }
433
434 }