remove the saved redirect when it's being used, always accept email scope
[authserver.git] / index.php
1 <?php
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
4  * You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6 // Include the common auth system files (including the OAuth2 Server object).
7 require_once(__DIR__.'/authsystem.inc.php');
8
9 // Start HTML document as a DOM object.
10 extract(ExtendedDocument::initHTML5()); // sets $document, $html, $head, $title, $body
11 $document->formatOutput = true; // we want a nice output
12
13 $style = $head->appendElement('link');
14 $style->setAttribute('rel', 'stylesheet');
15 $style->setAttribute('href', 'authsystem.css');
16 $head->appendJSFile('authsystem.js');
17 $title->appendText('KaiRo.at Authentication Server');
18 $h1 = $body->appendElement('h1', 'KaiRo.at Authentication Server');
19
20 $errors = $utils->checkForSecureConnection();
21
22 $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.'));
23 $para->setAttribute('id', 'jswarning');
24 $para->setAttribute('class', 'warn');
25
26 if (!count($errors)) {
27   $session = $utils->initSession(); // Read session or create new session and set cookie.
28   $user = array('id' => 0, 'email' => '');
29   $pagetype = 'default';
30   if (is_null($session)) {
31     $errors[] = _('The session system is not working. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
32   }
33   elseif (array_key_exists('logout', $_GET)) {
34     $result = $db->prepare('UPDATE `auth_sessions` SET `logged_in` = FALSE WHERE `id` = :sessid;');
35     if (!$result->execute(array(':sessid' => $session['id']))) {
36       $utils->log('logout_failure', 'session: '.$session['id']);
37       $errors[] = _('The email address is invalid.');
38     }
39     $session['logged_in'] = 0;
40   }
41   elseif (array_key_exists('email', $_POST)) {
42     if (!preg_match('/^[^@]+@[^@]+\.[^@]+$/', $_POST['email'])) {
43       $errors[] = _('The email address is invalid.');
44     }
45     elseif ($utils->verifyTimeCode(@$_POST['tcode'], $session)) {
46       $result = $db->prepare('SELECT `id`, `pwdhash`, `email`, `status`, `verify_hash` FROM `auth_users` WHERE `email` = :email;');
47       $result->execute(array(':email' => $_POST['email']));
48       $user = $result->fetch(PDO::FETCH_ASSOC);
49       if ($user['id'] && array_key_exists('pwd', $_POST)) {
50         // existing user, check password
51         if (($user['status'] == 'ok') && $utils->pwdVerify(@$_POST['pwd'], $user)) {
52           // Check if a newer hashing algorithm is available
53           // or the cost has changed
54           if ($utils->pwdNeedsRehash($user)) {
55             // If so, create a new hash, and replace the old one
56             $newHash = $utils->pwdHash($_POST['pwd']);
57             $result = $db->prepare('UPDATE `auth_users` SET `pwdhash` = :pwdhash WHERE `id` = :userid;');
58             if (!$result->execute(array(':pwdhash' => $newHash, ':userid' => $user['id']))) {
59               $utils->log('user_hash_save_failure', 'user: '.$user['id']);
60             }
61             else {
62               $utils->log('pwd_rehash_success', 'user: '.$user['id']);
63             }
64           }
65
66           // Log user in - update session key for that, see https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines#Login
67           $utils->log('login', 'user: '.$user['id']);
68           $sesskey = $utils->createSessionKey();
69           setcookie('sessionkey', $sesskey, 0, "", "", !$utils->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost.
70           // If the session has a redirect set, make sure it's performed.
71           if (strlen(@$session['saved_redirect'])) {
72             header('Location: '.$utils->getDomainBaseURL().$session['saved_redirect']);
73             // Remove redirect.
74             $result = $db->prepare('UPDATE `auth_sessions` SET `saved_redirect` = :redir WHERE `id` = :sessid;');
75             if (!$result->execute(array(':redir' => '', ':sessid' => $session['id']))) {
76               $utils->log('redir_save_failure', 'session: '.$session['id'].', redirect: (empty)');
77             }
78           }
79           // If the session has a user set, create a new one - otherwise take existing session entry.
80           if (intval($session['user'])) {
81             $result = $db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);');
82             $result->execute(array(':sesskey' => $sesskey, ':userid' => $user['id'], ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day'))));
83             // After insert, actually fetch the session row from the DB so we have all values.
84             $result = $db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
85             $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
86             $row = $result->fetch(PDO::FETCH_ASSOC);
87             if ($row) {
88               $session = $row;
89             }
90             else {
91               $utils->log('create_session_failure', 'at login, prev session: '.$session['id'].', new user: '.$user['id']);
92               $errors[] = _('The session system is not working. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
93             }
94           }
95           else {
96             $result = $db->prepare('UPDATE `auth_sessions` SET `sesskey` = :sesskey, `user` = :userid, `logged_in` = TRUE, `time_expire` = :expire WHERE `id` = :sessid;');
97             if (!$result->execute(array(':sesskey' => $sesskey, ':userid' => $user['id'], ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')), ':sessid' => $session['id']))) {
98               $utils->log('login_failure', 'session: '.$session['id'].', user: '.$user['id']);
99               $errors[] = _('Login failed unexpectedly. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
100             }
101             else {
102               // After update, actually fetch the session row from the DB so we have all values.
103               $result = $db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
104               $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
105               $row = $result->fetch(PDO::FETCH_ASSOC);
106               if ($row) {
107                 $session = $row;
108               }
109             }
110           }
111           // If a verify_hash if set on a verified user, a password reset had been requested. As a login works right now, cancel that reset request by deleting the hash.
112           if (strlen(@$user['verify_hash'])) {
113             $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = \'\' WHERE `id` = :userid;');
114             if (!$result->execute(array(':userid' => $user['id']))) {
115               $utils->log('empty_vhash_failure', 'user: '.$user['id']);
116             }
117             else {
118               $user['verify_hash'] = '';
119             }
120           }
121         }
122         else {
123           $errors[] = _('This password is invalid or your email is not verified yet. Did you type them correctly?');
124         }
125       }
126       else {
127         // new user: check password, create user and send verification; existing users: re-send verification or send password change instructions
128         if (array_key_exists('pwd', $_POST)) {
129           $errors += $utils->checkPasswordConstraints(strval($_POST['pwd']), $_POST['email']);
130         }
131         if (!count($errors)) {
132           // Put user into the DB
133           if (!$user['id']) {
134             $newHash = $utils->pwdHash($_POST['pwd']);
135             $vcode = $utils->createVerificationCode();
136             $result = $db->prepare('INSERT INTO `auth_users` (`email`, `pwdhash`, `status`, `verify_hash`) VALUES (:email, :pwdhash, \'unverified\', :vcode);');
137             if (!$result->execute(array(':email' => $_POST['email'], ':pwdhash' => $newHash, ':vcode' => $vcode))) {
138               $utils->log('user_insert_failure', 'email: '.$_POST['email']);
139               $errors[] = _('Could not add user. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
140             }
141             $user = array('id' => $db->lastInsertId(),
142                           'email' => $_POST['email'],
143                           'pwdhash' => $newHash,
144                           'status' => 'unverified',
145                           'verify_hash' => $vcode);
146             $utils->log('new_user', 'user: '.$user['id'].', email: '.$user['email']);
147           }
148           if ($user['status'] == 'unverified') {
149             // Send email for verification and show message to point to it.
150             $mail = new email();
151             $mail->setCharset('utf-8');
152             $mail->addHeader('X-KAIRO-AUTH', 'email_verification');
153             $mail->addRecipient($user['email']);
154             $mail->setSender('noreply@auth.kairo.at', _('KaiRo.at Authentication Service'));
155             $mail->setSubject('Email Verification for KaiRo.at Authentication');
156             $mail->addMailText(_('Welcome!')."\n\n");
157             $mail->addMailText(sprintf(_('This email address, %s, has been used for registration on "%s".'),
158                                       $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
159             $mail->addMailText(_('Please confirm that registration by clicking the following link (or calling it up in your browser):')."\n");
160             $mail->addMailText($utils->getDomainBaseURL().strstr($_SERVER['REQUEST_URI'], '?', true)
161                               .'?email='.rawurlencode($user['email']).'&verification_code='.rawurlencode($user['verify_hash'])."\n\n");
162             $mail->addMailText(_('With this confirmation, you accept that we handle your data for the purpose of logging you into other websites when you request that.')."\n");
163             $mail->addMailText(_('Those websites will get to know your email address but not your password, which we store securely.')."\n");
164             $mail->addMailText(_('If you do not call this confirmation link within 72 hours, your data will be deleted from our database.')."\n\n");
165             $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at'));
166             //$mail->setDebugAddress("robert@localhost");
167             $mailsent = $mail->send();
168             if ($mailsent) {
169               $pagetype = 'verification_sent';
170             }
171             else {
172               $utils->log('verify_mail_failure', 'user: '.$user['id'].', email: '.$user['email']);
173               $errors[] = _('The confirmation email could not be sent to you. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
174             }
175           }
176           else {
177             // Password reset requested with "Password forgotten?" function.
178             $vcode = $utils->createVerificationCode();
179             $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = :vcode WHERE `id` = :userid;');
180             if (!$result->execute(array(':vcode' => $vcode, ':userid' => $user['id']))) {
181               $utils->log('vhash_set_failure', 'user: '.$user['id']);
182               $errors[] = _('Could not initiate reset request. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
183             }
184             else {
185               $utils->log('pwd_reset_request', 'user: '.$user['id'].', email: '.$user['email']);
186               $resetcode = $vcode.dechex($user['id'] + $session['id']).'_'.$utils->createTimeCode($session, null, 60);
187               // Send email with instructions for resetting the password.
188               $mail = new email();
189               $mail->setCharset('utf-8');
190               $mail->addHeader('X-KAIRO-AUTH', 'password_reset');
191               $mail->addRecipient($user['email']);
192               $mail->setSender('noreply@auth.kairo.at', _('KaiRo.at Authentication Service'));
193               $mail->setSubject('How to reset your password for KaiRo.at Authentication');
194               $mail->addMailText(_('Hi,')."\n\n");
195               $mail->addMailText(sprintf(_('A request for setting a new password for this email address, %s, has been submitted on "%s".'),
196                                         $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
197               $mail->addMailText(_('You can set a new password by clicking the following link (or calling it up in your browser):')."\n");
198               $mail->addMailText($utils->getDomainBaseURL().strstr($_SERVER['REQUEST_URI'], '?', true)
199                                 .'?email='.rawurlencode($user['email']).'&reset_code='.rawurlencode($resetcode)."\n\n");
200               $mail->addMailText(_('If you do not call this confirmation link within 1 hour, this link expires and the existing password is being kept in place.')."\n\n");
201               $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at'));
202               //$mail->setDebugAddress("robert@localhost");
203               $mailsent = $mail->send();
204               if ($mailsent) {
205                 $pagetype = 'resetmail_sent';
206               }
207               else {
208                 $utils->log('pwd_reset_mail_failure', 'user: '.$user['id'].', email: '.$user['email']);
209                 $errors[] = _('The email with password reset instructions could not be sent to you. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
210               }
211             }
212           }
213         }
214       }
215     }
216     else {
217       $errors[] = _('The form you used was not valid. Possibly it has expired and you need to initiate the action again.');
218     }
219   }
220   elseif (array_key_exists('reset', $_GET)) {
221     if ($session['logged_in']) {
222       $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
223       $result->execute(array(':userid' => $session['user']));
224       $user = $result->fetch(PDO::FETCH_ASSOC);
225       if (!$user['id']) {
226         $utils->log('reset_user_read_failure', 'user: '.$session['user']);
227       }
228       $pagetype = 'resetpwd';
229     }
230     else {
231       // Display form for entering email.
232       $pagetype = 'resetstart';
233     }
234   }
235   elseif (array_key_exists('verification_code', $_GET)) {
236     $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `email` = :email AND `status` = \'unverified\' AND `verify_hash` = :vcode;');
237     $result->execute(array(':email' => @$_GET['email'], ':vcode' => $_GET['verification_code']));
238     $user = $result->fetch(PDO::FETCH_ASSOC);
239     if ($user['id']) {
240       $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = \'\', `status` = \'ok\' WHERE `id` = :userid;');
241       if (!$result->execute(array(':userid' => $user['id']))) {
242         $utils->log('verification_save_failure', 'user: '.$user['id']);
243         $errors[] = _('Could not save confirmation. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
244       }
245       $pagetype = 'verification_done';
246     }
247     else {
248       $errors[] = _('The confirmation link you called is not valid. Possibly it has expired and you need to try registering again.');
249     }
250   }
251   elseif (array_key_exists('reset_code', $_GET)) {
252     $reset_fail = true;
253     $result = $db->prepare('SELECT `id`,`email`,`verify_hash` FROM `auth_users` WHERE `email` = :email');
254     $result->execute(array(':email' => @$_GET['email']));
255     $user = $result->fetch(PDO::FETCH_ASSOC);
256     if ($user['id']) {
257       // Deconstruct reset code and verify it.
258       if (preg_match('/^([0-9a-f]{'.strlen($user['verify_hash']).'})([0-9a-f]+)_(\d+\.\d+)$/', $_GET['reset_code'], $regs)) {
259         $tcode_sessid = hexdec($regs[2]) - $user['id'];
260         $result = $db->prepare('SELECT `id`,`sesskey` FROM `auth_sessions` WHERE `id` = :sessid;');
261         $result->execute(array(':sessid' => $tcode_sessid));
262         $row = $result->fetch(PDO::FETCH_ASSOC);
263         if ($row) {
264           $tcode_session = $row;
265           if (($regs[1] == $user['verify_hash']) &&
266               $utils->verifyTimeCode($regs[3], $session, 60)) {
267             // Set a new verify_hash for the actual password reset.
268             $user['verify_hash'] = $utils->createVerificationCode();
269             $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = :vcode WHERE `id` = :userid;');
270             if (!$result->execute(array(':vcode' => $user['verify_hash'], ':userid' => $user['id']))) {
271               $utils->log('vhash_reset_failure', 'user: '.$user['id']);
272             }
273             $result = $db->prepare('UPDATE `auth_sessions` SET `user` = :userid WHERE `id` = :sessid;');
274             if (!$result->execute(array(':userid' => $user['id'], ':sessid' => $session['id']))) {
275               $utils->log('reset_session_set_user_failure', 'session: '.$session['id']);
276             }
277             $pagetype = 'resetpwd';
278             $reset_fail = false;
279           }
280         }
281       }
282     }
283     if ($reset_fail) {
284       $errors[] = _('The password reset link you called is not valid. Possibly it has expired and you need to call the "Password forgotten?" function again.');
285     }
286   }
287   elseif (intval($session['user'])) {
288     $result = $db->prepare('SELECT `id`,`email`,`verify_hash` FROM `auth_users` WHERE `id` = :userid;');
289     $result->execute(array(':userid' => $session['user']));
290     $user = $result->fetch(PDO::FETCH_ASSOC);
291     if (!$user['id']) {
292       $utils->log('user_read_failure', 'user: '.$session['user']);
293     }
294     // Password reset requested.
295     if (array_key_exists('pwd', $_POST) && array_key_exists('reset', $_POST) && array_key_exists('tcode', $_POST)) {
296       // If not logged in, a password reset needs to have the proper vcode set.
297       if (!$session['logged_in'] && (!strlen(@$_POST['vcode']) || ($_POST['vcode'] != $user['verify_hash']))) {
298         $errors[] = _('Password reset failed. The reset form you used was not valid. Possibly it has expired and you need to initiate the password reset again.');
299       }
300       // If not logged in, a password reset also needs to have the proper email set.
301       if (!$session['logged_in'] && !count($errors) && (@$_POST['email_hidden'] != $user['email'])) {
302         $errors[] = _('Password reset failed. The reset form you used was not valid. Possibly it has expired and you need to initiate the password reset again.');
303       }
304       // Check validity of time code.
305       if (!count($errors) && !$utils->verifyTimeCode($_POST['tcode'], $session)) {
306         $errors[] = _('Password reset failed. The reset form you used was not valid. Possibly it has expired and you need to initiate the password reset again.');
307       }
308       $errors += $utils->checkPasswordConstraints(strval($_POST['pwd']), $user['email']);
309       if (!count($errors)) {
310         $newHash = $utils->pwdHash($_POST['pwd']);
311         $result = $db->prepare('UPDATE `auth_users` SET `pwdhash` = :pwdhash, `verify_hash` = \'\' WHERE `id` = :userid;');
312         if (!$result->execute(array(':pwdhash' => $newHash, ':userid' => $session['user']))) {
313           $utils->log('pwd_reset_failure', 'user: '.$session['user']);
314           $errors[] = _('Password reset failed. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
315         }
316         else {
317           $pagetype = 'reset_done';
318         }
319       }
320     }
321   }
322 }
323
324 if (!count($errors)) {
325   if ($pagetype == 'verification_sent') {
326     $para = $body->appendElement('p', sprintf(_('An email for confirmation has been sent to %s. Please follow the link provided there to complete the process.'), $user['email']));
327     $para->setAttribute('class', 'verifyinfo pending');
328     $para = $body->appendElement('p', _('Reload this page after you confirm to continue.'));
329     $para->setAttribute('class', 'verifyinfo pending');
330   }
331   elseif ($pagetype == 'resetmail_sent') {
332     $para = $body->appendElement('p',
333         _('An email has been sent to the requested account with further information. If you do not receive an email then please confirm you have entered the same email address used during account registration.'));
334     $para->setAttribute('class', 'resetinfo pending');
335   }
336   elseif ($pagetype == 'resetstart') {
337     $para = $body->appendElement('p', _('If you forgot your password or didn\'t receive the registration confirmation, please enter your email here.'));
338     $para->setAttribute('class', '');
339     $form = $body->appendForm('./?reset', 'POST', 'resetform');
340     $form->setAttribute('id', 'loginform');
341     $form->setAttribute('class', 'loginarea hidden');
342     $ulist = $form->appendElement('ul');
343     $ulist->setAttribute('class', 'flat login');
344     $litem = $ulist->appendElement('li');
345     $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email');
346     $inptxt->setAttribute('autocomplete', 'email');
347     $inptxt->setAttribute('required', '');
348     $inptxt->setAttribute('placeholder', _('Email'));
349     $litem = $ulist->appendElement('li');
350     $litem->appendInputHidden('tcode', $utils->createTimeCode($session));
351     $submit = $litem->appendInputSubmit(_('Send instructions to email'));
352   }
353   elseif ($pagetype == 'resetpwd') {
354     $para = $body->appendElement('p', sprintf(_('You can set a new password for %s here.'), $user['email']));
355     $para->setAttribute('class', '');
356     $form = $body->appendForm('./', 'POST', 'newpwdform');
357     $form->setAttribute('id', 'loginform');
358     $form->setAttribute('class', 'loginarea hidden');
359     $ulist = $form->appendElement('ul');
360     $ulist->setAttribute('class', 'flat login');
361     $litem = $ulist->appendElement('li');
362     $litem->setAttribute('class', 'donotshow');
363     $inptxt = $litem->appendInputEmail('email_hidden', 30, 20, 'login_email', $user['email']);
364     $inptxt->setAttribute('autocomplete', 'email');
365     $inptxt->setAttribute('placeholder', _('Email'));
366     $litem = $ulist->appendElement('li');
367     $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', '');
368     $inptxt->setAttribute('required', '');
369     $inptxt->setAttribute('placeholder', _('Password'));
370     $inptxt->setAttribute('class', 'login');
371     $litem = $ulist->appendElement('li');
372     $litem->appendInputHidden('reset', '');
373     $litem->appendInputHidden('tcode', $utils->createTimeCode($session));
374     if (!$session['logged_in'] && strlen(@$user['verify_hash'])) {
375       $litem->appendInputHidden('vcode', $user['verify_hash']);
376     }
377     $submit = $litem->appendInputSubmit(_('Save password'));
378   }
379   elseif ($session['logged_in']) {
380     if ($pagetype == 'reset_done') {
381       $para = $body->appendElement('p', _('Your password has successfully been reset.'));
382       $para->setAttribute('class', 'resetinfo done');
383     }
384     $div = $body->appendElement('div', $user['email']);
385     $div->setAttribute('class', 'loginheader');
386     $div = $body->appendElement('div');
387     $div->setAttribute('class', 'loginlinks');
388     $ulist = $div->appendElement('ul');
389     $ulist->setAttribute('class', 'flat');
390     $litem = $ulist->appendElement('li');
391     $link = $litem->appendLink('./?logout', _('Log out'));
392     $litem = $ulist->appendElement('li');
393     $litem->appendLink('./?reset', _('Set new password'));
394   }
395   else { // not logged in
396     if ($pagetype == 'verification_done') {
397       $para = $body->appendElement('p', _('Hooray! Your email was successfully confirmed! You can log in now.'));
398       $para->setAttribute('class', 'verifyinfo done');
399     }
400     elseif ($pagetype == 'reset_done') {
401       $para = $body->appendElement('p', _('Your password has successfully been reset. You can log in now with the new password.'));
402       $para->setAttribute('class', 'resetinfo done');
403     }
404     $utils->appendLoginForm($body, $session, $user);
405   }
406 }
407
408 if (count($errors)) {
409   $body->appendElement('p', ((count($errors) <= 1)
410                             ?_('The following error was detected')
411                             :_('The following errors were detected')).':');
412   $list = $body->appendElement('ul');
413   $list->setAttribute('class', 'flat warn');
414   foreach ($errors as $msg) {
415     $item = $list->appendElement('li', $msg);
416   }
417   $body->appendButton(_('Back'), 'history.back();');
418 }
419
420 // Send HTML to client.
421 print($document->saveHTML());
422 ?>