make login on authorize actually work and redirect back to the authorize form after...
[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           }
74           // If the session has a user set, create a new one - otherwise take existing session entry.
75           if (intval($session['user'])) {
76             $result = $db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);');
77             $result->execute(array(':sesskey' => $sesskey, ':userid' => $user['id'], ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day'))));
78             // After insert, actually fetch the session row from the DB so we have all values.
79             $result = $db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
80             $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
81             $row = $result->fetch(PDO::FETCH_ASSOC);
82             if ($row) {
83               $session = $row;
84             }
85             else {
86               $utils->log('create_session_failure', 'at login, prev session: '.$session['id'].', new user: '.$user['id']);
87               $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.');
88             }
89           }
90           else {
91             $result = $db->prepare('UPDATE `auth_sessions` SET `sesskey` = :sesskey, `user` = :userid, `logged_in` = TRUE, `time_expire` = :expire WHERE `id` = :sessid;');
92             if (!$result->execute(array(':sesskey' => $sesskey, ':userid' => $user['id'], ':expire' => gmdate('Y-m-d H:i:s', strtotime('+1 day')), ':sessid' => $session['id']))) {
93               $utils->log('login_failure', 'session: '.$session['id'].', user: '.$user['id']);
94               $errors[] = _('Login failed unexpectedly. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
95             }
96             else {
97               // After update, actually fetch the session row from the DB so we have all values.
98               $result = $db->prepare('SELECT * FROM auth_sessions WHERE `sesskey` = :sesskey AND `time_expire` > :expire;');
99               $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s')));
100               $row = $result->fetch(PDO::FETCH_ASSOC);
101               if ($row) {
102                 $session = $row;
103               }
104             }
105           }
106           // 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.
107           if (strlen(@$user['verify_hash'])) {
108             $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = \'\' WHERE `id` = :userid;');
109             if (!$result->execute(array(':userid' => $user['id']))) {
110               $utils->log('empty_vhash_failure', 'user: '.$user['id']);
111             }
112             else {
113               $user['verify_hash'] = '';
114             }
115           }
116         }
117         else {
118           $errors[] = _('This password is invalid or your email is not verified yet. Did you type them correctly?');
119         }
120       }
121       else {
122         // new user: check password, create user and send verification; existing users: re-send verification or send password change instructions
123         if (array_key_exists('pwd', $_POST)) {
124           $errors += $utils->checkPasswordConstraints(strval($_POST['pwd']), $_POST['email']);
125         }
126         if (!count($errors)) {
127           // Put user into the DB
128           if (!$user['id']) {
129             $newHash = $utils->pwdHash($_POST['pwd']);
130             $vcode = $utils->createVerificationCode();
131             $result = $db->prepare('INSERT INTO `auth_users` (`email`, `pwdhash`, `status`, `verify_hash`) VALUES (:email, :pwdhash, \'unverified\', :vcode);');
132             if (!$result->execute(array(':email' => $_POST['email'], ':pwdhash' => $newHash, ':vcode' => $vcode))) {
133               $utils->log('user_insert_failure', 'email: '.$_POST['email']);
134               $errors[] = _('Could not add user. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
135             }
136             $user = array('id' => $db->lastInsertId(),
137                           'email' => $_POST['email'],
138                           'pwdhash' => $newHash,
139                           'status' => 'unverified',
140                           'verify_hash' => $vcode);
141             $utils->log('new_user', 'user: '.$user['id'].', email: '.$user['email']);
142           }
143           if ($user['status'] == 'unverified') {
144             // Send email for verification and show message to point to it.
145             $mail = new email();
146             $mail->setCharset('utf-8');
147             $mail->addHeader('X-KAIRO-AUTH', 'email_verification');
148             $mail->addRecipient($user['email']);
149             $mail->setSender('noreply@auth.kairo.at', _('KaiRo.at Authentication Service'));
150             $mail->setSubject('Email Verification for KaiRo.at Authentication');
151             $mail->addMailText(_('Welcome!')."\n\n");
152             $mail->addMailText(sprintf(_('This email address, %s, has been used for registration on "%s".'),
153                                       $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
154             $mail->addMailText(_('Please confirm that registration by clicking the following link (or calling it up in your browser):')."\n");
155             $mail->addMailText($utils->getDomainBaseURL().strstr($_SERVER['REQUEST_URI'], '?', true)
156                               .'?email='.rawurlencode($user['email']).'&verification_code='.rawurlencode($user['verify_hash'])."\n\n");
157             $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");
158             $mail->addMailText(_('Those websites will get to know your email address but not your password, which we store securely.')."\n");
159             $mail->addMailText(_('If you do not call this confirmation link within 72 hours, your data will be deleted from our database.')."\n\n");
160             $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at'));
161             //$mail->setDebugAddress("robert@localhost");
162             $mailsent = $mail->send();
163             if ($mailsent) {
164               $pagetype = 'verification_sent';
165             }
166             else {
167               $utils->log('verify_mail_failure', 'user: '.$user['id'].', email: '.$user['email']);
168               $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.');
169             }
170           }
171           else {
172             // Password reset requested with "Password forgotten?" function.
173             $vcode = $utils->createVerificationCode();
174             $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = :vcode WHERE `id` = :userid;');
175             if (!$result->execute(array(':vcode' => $vcode, ':userid' => $user['id']))) {
176               $utils->log('vhash_set_failure', 'user: '.$user['id']);
177               $errors[] = _('Could not initiate reset request. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
178             }
179             else {
180               $utils->log('pwd_reset_request', 'user: '.$user['id'].', email: '.$user['email']);
181               $resetcode = $vcode.dechex($user['id'] + $session['id']).'_'.$utils->createTimeCode($session, null, 60);
182               // Send email with instructions for resetting the password.
183               $mail = new email();
184               $mail->setCharset('utf-8');
185               $mail->addHeader('X-KAIRO-AUTH', 'password_reset');
186               $mail->addRecipient($user['email']);
187               $mail->setSender('noreply@auth.kairo.at', _('KaiRo.at Authentication Service'));
188               $mail->setSubject('How to reset your password for KaiRo.at Authentication');
189               $mail->addMailText(_('Hi,')."\n\n");
190               $mail->addMailText(sprintf(_('A request for setting a new password for this email address, %s, has been submitted on "%s".'),
191                                         $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
192               $mail->addMailText(_('You can set a new password by clicking the following link (or calling it up in your browser):')."\n");
193               $mail->addMailText($utils->getDomainBaseURL().strstr($_SERVER['REQUEST_URI'], '?', true)
194                                 .'?email='.rawurlencode($user['email']).'&reset_code='.rawurlencode($resetcode)."\n\n");
195               $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");
196               $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at'));
197               //$mail->setDebugAddress("robert@localhost");
198               $mailsent = $mail->send();
199               if ($mailsent) {
200                 $pagetype = 'resetmail_sent';
201               }
202               else {
203                 $utils->log('pwd_reset_mail_failure', 'user: '.$user['id'].', email: '.$user['email']);
204                 $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.');
205               }
206             }
207           }
208         }
209       }
210     }
211     else {
212       $errors[] = _('The form you used was not valid. Possibly it has expired and you need to initiate the action again.');
213     }
214   }
215   elseif (array_key_exists('reset', $_GET)) {
216     if ($session['logged_in']) {
217       $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
218       $result->execute(array(':userid' => $session['user']));
219       $user = $result->fetch(PDO::FETCH_ASSOC);
220       if (!$user['id']) {
221         $utils->log('reset_user_read_failure', 'user: '.$session['user']);
222       }
223       $pagetype = 'resetpwd';
224     }
225     else {
226       // Display form for entering email.
227       $pagetype = 'resetstart';
228     }
229   }
230   elseif (array_key_exists('verification_code', $_GET)) {
231     $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `email` = :email AND `status` = \'unverified\' AND `verify_hash` = :vcode;');
232     $result->execute(array(':email' => @$_GET['email'], ':vcode' => $_GET['verification_code']));
233     $user = $result->fetch(PDO::FETCH_ASSOC);
234     if ($user['id']) {
235       $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = \'\', `status` = \'ok\' WHERE `id` = :userid;');
236       if (!$result->execute(array(':userid' => $user['id']))) {
237         $utils->log('verification_save_failure', 'user: '.$user['id']);
238         $errors[] = _('Could not save confirmation. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
239       }
240       $pagetype = 'verification_done';
241     }
242     else {
243       $errors[] = _('The confirmation link you called is not valid. Possibly it has expired and you need to try registering again.');
244     }
245   }
246   elseif (array_key_exists('reset_code', $_GET)) {
247     $reset_fail = true;
248     $result = $db->prepare('SELECT `id`,`email`,`verify_hash` FROM `auth_users` WHERE `email` = :email');
249     $result->execute(array(':email' => @$_GET['email']));
250     $user = $result->fetch(PDO::FETCH_ASSOC);
251     if ($user['id']) {
252       // Deconstruct reset code and verify it.
253       if (preg_match('/^([0-9a-f]{'.strlen($user['verify_hash']).'})([0-9a-f]+)_(\d+\.\d+)$/', $_GET['reset_code'], $regs)) {
254         $tcode_sessid = hexdec($regs[2]) - $user['id'];
255         $result = $db->prepare('SELECT `id`,`sesskey` FROM `auth_sessions` WHERE `id` = :sessid;');
256         $result->execute(array(':sessid' => $tcode_sessid));
257         $row = $result->fetch(PDO::FETCH_ASSOC);
258         if ($row) {
259           $tcode_session = $row;
260           if (($regs[1] == $user['verify_hash']) &&
261               $utils->verifyTimeCode($regs[3], $session, 60)) {
262             // Set a new verify_hash for the actual password reset.
263             $user['verify_hash'] = $utils->createVerificationCode();
264             $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = :vcode WHERE `id` = :userid;');
265             if (!$result->execute(array(':vcode' => $user['verify_hash'], ':userid' => $user['id']))) {
266               $utils->log('vhash_reset_failure', 'user: '.$user['id']);
267             }
268             $result = $db->prepare('UPDATE `auth_sessions` SET `user` = :userid WHERE `id` = :sessid;');
269             if (!$result->execute(array(':userid' => $user['id'], ':sessid' => $session['id']))) {
270               $utils->log('reset_session_set_user_failure', 'session: '.$session['id']);
271             }
272             $pagetype = 'resetpwd';
273             $reset_fail = false;
274           }
275         }
276       }
277     }
278     if ($reset_fail) {
279       $errors[] = _('The password reset link you called is not valid. Possibly it has expired and you need to call the "Password forgotten?" function again.');
280     }
281   }
282   elseif (intval($session['user'])) {
283     $result = $db->prepare('SELECT `id`,`email`,`verify_hash` FROM `auth_users` WHERE `id` = :userid;');
284     $result->execute(array(':userid' => $session['user']));
285     $user = $result->fetch(PDO::FETCH_ASSOC);
286     if (!$user['id']) {
287       $utils->log('user_read_failure', 'user: '.$session['user']);
288     }
289     // Password reset requested.
290     if (array_key_exists('pwd', $_POST) && array_key_exists('reset', $_POST) && array_key_exists('tcode', $_POST)) {
291       // If not logged in, a password reset needs to have the proper vcode set.
292       if (!$session['logged_in'] && (!strlen(@$_POST['vcode']) || ($_POST['vcode'] != $user['verify_hash']))) {
293         $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.');
294       }
295       // If not logged in, a password reset also needs to have the proper email set.
296       if (!$session['logged_in'] && !count($errors) && (@$_POST['email_hidden'] != $user['email'])) {
297         $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.');
298       }
299       // Check validity of time code.
300       if (!count($errors) && !$utils->verifyTimeCode($_POST['tcode'], $session)) {
301         $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.');
302       }
303       $errors += $utils->checkPasswordConstraints(strval($_POST['pwd']), $user['email']);
304       if (!count($errors)) {
305         $newHash = $utils->pwdHash($_POST['pwd']);
306         $result = $db->prepare('UPDATE `auth_users` SET `pwdhash` = :pwdhash, `verify_hash` = \'\' WHERE `id` = :userid;');
307         if (!$result->execute(array(':pwdhash' => $newHash, ':userid' => $session['user']))) {
308           $utils->log('pwd_reset_failure', 'user: '.$session['user']);
309           $errors[] = _('Password reset failed. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
310         }
311         else {
312           $pagetype = 'reset_done';
313         }
314       }
315     }
316   }
317 }
318
319 if (!count($errors)) {
320   if ($pagetype == 'verification_sent') {
321     $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']));
322     $para->setAttribute('class', 'verifyinfo pending');
323     $para = $body->appendElement('p', _('Reload this page after you confirm to continue.'));
324     $para->setAttribute('class', 'verifyinfo pending');
325   }
326   elseif ($pagetype == 'resetmail_sent') {
327     $para = $body->appendElement('p',
328         _('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.'));
329     $para->setAttribute('class', 'resetinfo pending');
330   }
331   elseif ($pagetype == 'resetstart') {
332     $para = $body->appendElement('p', _('If you forgot your password or didn\'t receive the registration confirmation, please enter your email here.'));
333     $para->setAttribute('class', '');
334     $form = $body->appendForm('./?reset', 'POST', 'resetform');
335     $form->setAttribute('id', 'loginform');
336     $form->setAttribute('class', 'loginarea hidden');
337     $ulist = $form->appendElement('ul');
338     $ulist->setAttribute('class', 'flat login');
339     $litem = $ulist->appendElement('li');
340     $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email');
341     $inptxt->setAttribute('autocomplete', 'email');
342     $inptxt->setAttribute('required', '');
343     $inptxt->setAttribute('placeholder', _('Email'));
344     $litem = $ulist->appendElement('li');
345     $litem->appendInputHidden('tcode', $utils->createTimeCode($session));
346     $submit = $litem->appendInputSubmit(_('Send instructions to email'));
347   }
348   elseif ($pagetype == 'resetpwd') {
349     $para = $body->appendElement('p', sprintf(_('You can set a new password for %s here.'), $user['email']));
350     $para->setAttribute('class', '');
351     $form = $body->appendForm('./', 'POST', 'newpwdform');
352     $form->setAttribute('id', 'loginform');
353     $form->setAttribute('class', 'loginarea hidden');
354     $ulist = $form->appendElement('ul');
355     $ulist->setAttribute('class', 'flat login');
356     $litem = $ulist->appendElement('li');
357     $litem->setAttribute('class', 'donotshow');
358     $inptxt = $litem->appendInputEmail('email_hidden', 30, 20, 'login_email', $user['email']);
359     $inptxt->setAttribute('autocomplete', 'email');
360     $inptxt->setAttribute('placeholder', _('Email'));
361     $litem = $ulist->appendElement('li');
362     $inptxt = $litem->appendInputPassword('pwd', 20, 20, 'login_pwd', '');
363     $inptxt->setAttribute('required', '');
364     $inptxt->setAttribute('placeholder', _('Password'));
365     $inptxt->setAttribute('class', 'login');
366     $litem = $ulist->appendElement('li');
367     $litem->appendInputHidden('reset', '');
368     $litem->appendInputHidden('tcode', $utils->createTimeCode($session));
369     if (!$session['logged_in'] && strlen(@$user['verify_hash'])) {
370       $litem->appendInputHidden('vcode', $user['verify_hash']);
371     }
372     $submit = $litem->appendInputSubmit(_('Save password'));
373   }
374   elseif ($session['logged_in']) {
375     if ($pagetype == 'reset_done') {
376       $para = $body->appendElement('p', _('Your password has successfully been reset.'));
377       $para->setAttribute('class', 'resetinfo done');
378     }
379     $div = $body->appendElement('div', $user['email']);
380     $div->setAttribute('class', 'loginheader');
381     $div = $body->appendElement('div');
382     $div->setAttribute('class', 'loginlinks');
383     $ulist = $div->appendElement('ul');
384     $ulist->setAttribute('class', 'flat');
385     $litem = $ulist->appendElement('li');
386     $link = $litem->appendLink('./?logout', _('Log out'));
387     $litem = $ulist->appendElement('li');
388     $litem->appendLink('./?reset', _('Set new password'));
389   }
390   else { // not logged in
391     if ($pagetype == 'verification_done') {
392       $para = $body->appendElement('p', _('Hooray! Your email was successfully confirmed! You can log in now.'));
393       $para->setAttribute('class', 'verifyinfo done');
394     }
395     elseif ($pagetype == 'reset_done') {
396       $para = $body->appendElement('p', _('Your password has successfully been reset. You can log in now with the new password.'));
397       $para->setAttribute('class', 'resetinfo done');
398     }
399     $utils->appendLoginForm($body, $session, $user);
400   }
401 }
402
403 if (count($errors)) {
404   $body->appendElement('p', ((count($errors) <= 1)
405                             ?_('The following error was detected')
406                             :_('The following errors were detected')).':');
407   $list = $body->appendElement('ul');
408   $list->setAttribute('class', 'flat warn');
409   foreach ($errors as $msg) {
410     $item = $list->appendElement('li', $msg);
411   }
412   $body->appendButton(_('Back'), 'history.back();');
413 }
414
415 // Send HTML to client.
416 print($document->saveHTML());
417 ?>