]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/finishopenidlogin.php
1f9bde0f157959fc86fd5e98ea26a798b9b49102
[quix0rs-gnu-social.git] / plugins / OpenID / finishopenidlogin.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 require_once INSTALLDIR.'/plugins/OpenID/openid.php';
23
24 class FinishopenidloginAction extends Action
25 {
26     var $error = null;
27     var $username = null;
28     var $message = null;
29
30     function handle($args)
31     {
32         parent::handle($args);
33         if (common_is_real_login()) {
34             $this->clientError(_m('Already logged in.'));
35         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
36             $token = $this->trimmed('token');
37             if (!$token || $token != common_session_token()) {
38                 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
39                 return;
40             }
41             if ($this->arg('create')) {
42                 if (!$this->boolean('license')) {
43                     $this->showForm(_m('You can\'t register if you don\'t agree to the license.'),
44                                     $this->trimmed('newname'));
45                     return;
46                 }
47                 $this->createNewUser();
48             } else if ($this->arg('connect')) {
49                 $this->connectUser();
50             } else {
51                 $this->showForm(_m('Something weird happened.'),
52                                 $this->trimmed('newname'));
53             }
54         } else {
55             $this->tryLogin();
56         }
57     }
58
59     function showPageNotice()
60     {
61         if ($this->error) {
62             $this->element('div', array('class' => 'error'), $this->error);
63         } else {
64             $this->element('div', 'instructions',
65                            sprintf(_m('This is the first time you\'ve logged into %s so we must connect your OpenID to a local account. You can either create a new account, or connect with your existing account, if you have one.'), common_config('site', 'name')));
66         }
67     }
68
69     function title()
70     {
71         return _m('OpenID Account Setup');
72     }
73
74     function showForm($error=null, $username=null)
75     {
76         $this->error = $error;
77         $this->username = $username;
78
79         $this->showPage();
80     }
81
82     function showContent()
83     {
84         if (!empty($this->message_text)) {
85             $this->element('div', array('class' => 'error'), $this->message_text);
86             return;
87         }
88
89         $this->elementStart('form', array('method' => 'post',
90                                           'id' => 'account_connect',
91                                           'class' => 'form_settings',
92                                           'action' => common_local_url('finishopenidlogin')));
93         $this->hidden('token', common_session_token());
94         $this->elementStart('fieldset', array('id' => 'form_openid_createaccount'));
95         $this->element('legend', null,
96                        _m('Create new account'));
97         $this->element('p', null,
98                        _m('Create a new user with this nickname.'));
99         $this->elementStart('ul', 'form_data');
100         $this->elementStart('li');
101         $this->input('newname', _m('New nickname'),
102                      ($this->username) ? $this->username : '',
103                      _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
104         $this->elementEnd('li');
105         $this->elementStart('li');
106         $this->element('input', array('type' => 'checkbox',
107                                       'id' => 'license',
108                                       'class' => 'checkbox',
109                                       'name' => 'license',
110                                       'value' => 'true'));
111         $this->elementStart('label', array('for' => 'license',
112                                           'class' => 'checkbox'));
113         $this->text(_m('My text and files are available under '));
114         $this->element('a', array('href' => common_config('license', 'url')),
115                        common_config('license', 'title'));
116         $this->text(_m(' except this private data: password, email address, IM address, phone number.'));
117         $this->elementEnd('label');
118         $this->elementEnd('li');
119         $this->elementEnd('ul');
120         $this->submit('create', _m('Create'));
121         $this->elementEnd('fieldset');
122
123         $this->elementStart('fieldset', array('id' => 'form_openid_createaccount'));
124         $this->element('legend', null,
125                        _m('Connect existing account'));
126         $this->element('p', null,
127                        _m('If you already have an account, login with your username and password to connect it to your OpenID.'));
128         $this->elementStart('ul', 'form_data');
129         $this->elementStart('li');
130         $this->input('nickname', _m('Existing nickname'));
131         $this->elementEnd('li');
132         $this->elementStart('li');
133         $this->password('password', _m('Password'));
134         $this->elementEnd('li');
135         $this->elementEnd('ul');
136         $this->submit('connect', _m('Connect'));
137         $this->elementEnd('fieldset');
138         $this->elementEnd('form');
139     }
140
141     function tryLogin()
142     {
143         $consumer = oid_consumer();
144
145         $response = $consumer->complete(common_local_url('finishopenidlogin'));
146
147         if ($response->status == Auth_OpenID_CANCEL) {
148             $this->message(_m('OpenID authentication cancelled.'));
149             return;
150         } else if ($response->status == Auth_OpenID_FAILURE) {
151             // Authentication failed; display the error message.
152             $this->message(sprintf(_m('OpenID authentication failed: %s'), $response->message));
153         } else if ($response->status == Auth_OpenID_SUCCESS) {
154             // This means the authentication succeeded; extract the
155             // identity URL and Simple Registration data (if it was
156             // returned).
157             $display = $response->getDisplayIdentifier();
158             $canonical = ($response->endpoint->canonicalID) ?
159               $response->endpoint->canonicalID : $response->getDisplayIdentifier();
160
161             $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
162
163             if ($sreg_resp) {
164                 $sreg = $sreg_resp->contents();
165             }
166
167             $user = oid_get_user($canonical);
168
169             if ($user) {
170                 oid_set_last($display);
171                 # XXX: commented out at @edd's request until better
172                 # control over how data flows from OpenID provider.
173                 # oid_update_user($user, $sreg);
174                 common_set_user($user);
175                 common_real_login(true);
176                 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
177                     common_rememberme($user);
178                 }
179                 unset($_SESSION['openid_rememberme']);
180                 $this->goHome($user->nickname);
181             } else {
182                 $this->saveValues($display, $canonical, $sreg);
183                 $this->showForm(null, $this->bestNewNickname($display, $sreg));
184             }
185         }
186     }
187
188     function message($msg)
189     {
190         $this->message_text = $msg;
191         $this->showPage();
192     }
193
194     function saveValues($display, $canonical, $sreg)
195     {
196         common_ensure_session();
197         $_SESSION['openid_display'] = $display;
198         $_SESSION['openid_canonical'] = $canonical;
199         $_SESSION['openid_sreg'] = $sreg;
200     }
201
202     function getSavedValues()
203     {
204         return array($_SESSION['openid_display'],
205                      $_SESSION['openid_canonical'],
206                      $_SESSION['openid_sreg']);
207     }
208
209     function createNewUser()
210     {
211         # FIXME: save invite code before redirect, and check here
212
213         if (common_config('site', 'closed')) {
214             $this->clientError(_m('Registration not allowed.'));
215             return;
216         }
217
218         $invite = null;
219
220         if (common_config('site', 'inviteonly')) {
221             $code = $_SESSION['invitecode'];
222             if (empty($code)) {
223                 $this->clientError(_m('Registration not allowed.'));
224                 return;
225             }
226
227             $invite = Invitation::staticGet($code);
228
229             if (empty($invite)) {
230                 $this->clientError(_m('Not a valid invitation code.'));
231                 return;
232             }
233         }
234
235         $nickname = $this->trimmed('newname');
236
237         if (!Validate::string($nickname, array('min_length' => 1,
238                                                'max_length' => 64,
239                                                'format' => NICKNAME_FMT))) {
240             $this->showForm(_m('Nickname must have only lowercase letters and numbers and no spaces.'));
241             return;
242         }
243
244         if (!User::allowed_nickname($nickname)) {
245             $this->showForm(_m('Nickname not allowed.'));
246             return;
247         }
248
249         if (User::staticGet('nickname', $nickname)) {
250             $this->showForm(_m('Nickname already in use. Try another one.'));
251             return;
252         }
253
254         list($display, $canonical, $sreg) = $this->getSavedValues();
255
256         if (!$display || !$canonical) {
257             $this->serverError(_m('Stored OpenID not found.'));
258             return;
259         }
260
261         # Possible race condition... let's be paranoid
262
263         $other = oid_get_user($canonical);
264
265         if ($other) {
266             $this->serverError(_m('Creating new account for OpenID that already has a user.'));
267             return;
268         }
269
270         $location = '';
271         if (!empty($sreg['country'])) {
272             if ($sreg['postcode']) {
273                 # XXX: use postcode to get city and region
274                 # XXX: also, store postcode somewhere -- it's valuable!
275                 $location = $sreg['postcode'] . ', ' . $sreg['country'];
276             } else {
277                 $location = $sreg['country'];
278             }
279         }
280
281         if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
282             $fullname = $sreg['fullname'];
283         } else {
284             $fullname = '';
285         }
286
287         if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
288             $email = $sreg['email'];
289         } else {
290             $email = '';
291         }
292
293         # XXX: add language
294         # XXX: add timezone
295
296         $args = array('nickname' => $nickname,
297                       'email' => $email,
298                       'fullname' => $fullname,
299                       'location' => $location);
300
301         if (!empty($invite)) {
302             $args['code'] = $invite->code;
303         }
304
305         $user = User::register($args);
306
307         $result = oid_link_user($user->id, $canonical, $display);
308
309         oid_set_last($display);
310         common_set_user($user);
311         common_real_login(true);
312         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
313             common_rememberme($user);
314         }
315         unset($_SESSION['openid_rememberme']);
316         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
317                         303);
318     }
319
320     function connectUser()
321     {
322         $nickname = $this->trimmed('nickname');
323         $password = $this->trimmed('password');
324
325         if (!common_check_user($nickname, $password)) {
326             $this->showForm(_m('Invalid username or password.'));
327             return;
328         }
329
330         # They're legit!
331
332         $user = User::staticGet('nickname', $nickname);
333
334         list($display, $canonical, $sreg) = $this->getSavedValues();
335
336         if (!$display || !$canonical) {
337             $this->serverError(_m('Stored OpenID not found.'));
338             return;
339         }
340
341         $result = oid_link_user($user->id, $canonical, $display);
342
343         if (!$result) {
344             $this->serverError(_m('Error connecting user to OpenID.'));
345             return;
346         }
347
348         oid_update_user($user, $sreg);
349         oid_set_last($display);
350         common_set_user($user);
351         common_real_login(true);
352         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
353             common_rememberme($user);
354         }
355         unset($_SESSION['openid_rememberme']);
356         $this->goHome($user->nickname);
357     }
358
359     function goHome($nickname)
360     {
361         $url = common_get_returnto();
362         if ($url) {
363             # We don't have to return to it again
364             common_set_returnto(null);
365             $url = common_inject_session($url);
366         } else {
367             $url = common_local_url('all',
368                                     array('nickname' =>
369                                           $nickname));
370         }
371         common_redirect($url, 303);
372     }
373
374     function bestNewNickname($display, $sreg)
375     {
376
377         # Try the passed-in nickname
378
379         if (!empty($sreg['nickname'])) {
380             $nickname = $this->nicknamize($sreg['nickname']);
381             if ($this->isNewNickname($nickname)) {
382                 return $nickname;
383             }
384         }
385
386         # Try the full name
387
388         if (!empty($sreg['fullname'])) {
389             $fullname = $this->nicknamize($sreg['fullname']);
390             if ($this->isNewNickname($fullname)) {
391                 return $fullname;
392             }
393         }
394
395         # Try the URL
396
397         $from_url = $this->openidToNickname($display);
398
399         if ($from_url && $this->isNewNickname($from_url)) {
400             return $from_url;
401         }
402
403         # XXX: others?
404
405         return null;
406     }
407
408     function isNewNickname($str)
409     {
410         if (!Validate::string($str, array('min_length' => 1,
411                                           'max_length' => 64,
412                                           'format' => NICKNAME_FMT))) {
413             return false;
414         }
415         if (!User::allowed_nickname($str)) {
416             return false;
417         }
418         if (User::staticGet('nickname', $str)) {
419             return false;
420         }
421         return true;
422     }
423
424     function openidToNickname($openid)
425     {
426         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
427             return $this->xriToNickname($openid);
428         } else {
429             return $this->urlToNickname($openid);
430         }
431     }
432
433     # We try to use an OpenID URL as a legal StatusNet user name in this order
434     # 1. Plain hostname, like http://evanp.myopenid.com/
435     # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
436     #    or http://getopenid.com/evanprodromou
437
438     function urlToNickname($openid)
439     {
440         return common_url_to_nickname($openid);
441     }
442
443     function xriToNickname($xri)
444     {
445         $base = $this->xriBase($xri);
446
447         if (!$base) {
448             return null;
449         } else {
450             # =evan.prodromou
451             # or @gratis*evan.prodromou
452             $parts = explode('*', substr($base, 1));
453             return $this->nicknamize(array_pop($parts));
454         }
455     }
456
457     function xriBase($xri)
458     {
459         if (substr($xri, 0, 6) == 'xri://') {
460             return substr($xri, 6);
461         } else {
462             return $xri;
463         }
464     }
465
466     # Given a string, try to make it work as a nickname
467
468     function nicknamize($str)
469     {
470         return common_nicknamize($str);
471     }
472 }