add a human check to registrations
[authserver.git] / app / index.php
index 5f091a26ae14b152d49f79e44f3f0ca145b1ea83..5ca41965925ce3bfb142dea2dba9df21dd473d60 100644 (file)
@@ -6,35 +6,19 @@
 // Include the common auth system files (including the OAuth2 Server object).
 require_once(__DIR__.'/authsystem.inc.php');
 
-// Start HTML document as a DOM object.
-extract(ExtendedDocument::initHTML5()); // sets $document, $html, $head, $title, $body
-$document->formatOutput = true; // we want a nice output
-
-$style = $head->appendElement('link');
-$style->setAttribute('rel', 'stylesheet');
-$style->setAttribute('href', 'authsystem.css');
-$head->appendJSFile('authsystem.js');
-$title->appendText('KaiRo.at Authentication Server');
-$h1 = $body->appendElement('h1', 'KaiRo.at Authentication Server');
-
-// Make the document not be scaled on mobile devices.
-$vpmeta = $head->appendElement('meta');
-$vpmeta->setAttribute('name', 'viewport');
-$vpmeta->setAttribute('content', 'width=device-width, height=device-height');
-
 $errors = $utils->checkForSecureConnection();
 $utils->sendSecurityHeaders();
 
-$para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.'));
-$para->setAttribute('id', 'jswarning');
-$para->setAttribute('class', 'warn');
+// Initialize the HTML document with our basic elements.
+extract($utils->initHTMLDocument(sprintf(_('%s Authentication Server'), $utils->settings['operator_name']))); // sets $document, $html, $head, $title, $body
 
 if (!count($errors)) {
   $session = $utils->initSession(); // Read session or create new session and set cookie.
   $user = array('id' => 0, 'email' => '');
   $pagetype = 'default';
   if (is_null($session)) {
-    $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.');
+    $errors[] = _('The session system is not working.').' '
+                .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
   }
   elseif (array_key_exists('logout', $_GET)) {
     $result = $db->prepare('UPDATE `auth_sessions` SET `logged_in` = FALSE WHERE `id` = :sessid;');
@@ -45,16 +29,19 @@ if (!count($errors)) {
     $session['logged_in'] = 0;
   }
   elseif (array_key_exists('email', $_POST)) {
-    if (!preg_match('/^[^@]+@[^@]+\.[^@]+$/', $_POST['email'])) {
+    if (!preg_match('/^[^@]+@([^@]+\.[^@]+|localhost)$/', $_POST['email'])) {
       $errors[] = _('The email address is invalid.');
     }
-    elseif ($utils->verifyTimeCode(@$_POST['tcode'], $session)) {
-      $result = $db->prepare('SELECT `id`, `pwdhash`, `email`, `status`, `verify_hash`,`group_id` FROM `auth_users` WHERE `email` = :email;');
+    elseif ($utils->verifyTimeCode($_POST['tcode'] ?? '', $session)) {
+      $result = $db->prepare('SELECT `id`, `pwdhash`, `email`, `status`, `verify_hash`, `group_id`, `hcheck_question`, `hcheck_solution` FROM `auth_users` WHERE `email` = :email;');
       $result->execute(array(':email' => $_POST['email']));
-      $user = $result->fetch(PDO::FETCH_ASSOC);
+      $user_data = $result->fetch(PDO::FETCH_ASSOC);
+      if ($user_data) {
+        $user = $user_data;
+      }
       // If we need to add the email to a group, note here which user's group we should be added to - otherwise, set to 0.
       $addgroup = (array_key_exists('grouptoexisting', $_POST) && intval($session['user']) && ($session['user'] != @$user['id'])) ? $session['user'] : 0;
-      if ($user['id'] && array_key_exists('pwd', $_POST)) {
+      if ($user['id'] && $user['status'] != 'unchecked' && array_key_exists('pwd', $_POST)) {
         // existing user, check password
         if (($user['status'] == 'ok') && $utils->pwdVerify(@$_POST['pwd'], $user)) {
           // Check if a newer hashing algorithm is available
@@ -101,36 +88,78 @@ if (!count($errors)) {
           if (!$user['id']) {
             $newHash = $utils->pwdHash($_POST['pwd']);
             $vcode = $utils->createVerificationCode();
-            $result = $db->prepare('INSERT INTO `auth_users` (`email`, `pwdhash`, `status`, `verify_hash`) VALUES (:email, :pwdhash, \'unverified\', :vcode);');
-            if (!$result->execute(array(':email' => $_POST['email'], ':pwdhash' => $newHash, ':vcode' => $vcode))) {
+            $result = $db->prepare('INSERT INTO `auth_users` (`email`, `pwdhash`, `status`, `verify_hash`) VALUES (:email, :pwdhash, :status, :vcode);');
+            if (!$result->execute(array(':email' => $_POST['email'], ':pwdhash' => $newHash, ':status' => 'unchecked', ':vcode' => $vcode))) {
               $utils->log('user_insert_failure', 'email: '.$_POST['email'].' - '.$result->errorInfo()[2]);
-              $errors[] = _('Could not add user. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
+              $errors[] = _('Could not add user.').' '
+                          .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
             }
-            $user = array('id' => $db->lastInsertId(),
-                          'email' => $_POST['email'],
-                          'pwdhash' => $newHash,
-                          'status' => 'unverified',
-                          'verify_hash' => $vcode);
+            $user = [
+              'id' => $db->lastInsertId(),
+              'email' => $_POST['email'],
+              'pwdhash' => $newHash,
+              'status' => 'unchecked',
+              'verify_hash' => $vcode,
+              'hcheck_question' => null,
+              'hcheck_solution' => null,
+            ];
             $utils->log('new_user', 'user: '.$user['id'].', email: '.$user['email']);
           }
-          if ($user['status'] == 'unverified') {
+          $utils->log('user_log_check', 'user: '.$user['id'].', email: '.$user['email'].', status: '.$user['status']);
+          if ($user['status'] == 'unchecked' && !is_null($user['hcheck_question']) && array_key_exists('hcheck_solution', $_POST)) {
+            if ($_POST['hcheck_solution'] == $user['hcheck_solution']) {
+              $result = $db->prepare('UPDATE `auth_users` SET `status` = :status, `hcheck_question` = :hcquestion, `hcheck_solution` = :hcsolution WHERE `id` = :userid;');
+              if (!$result->execute(array(':status' => 'unverified', ':hcquestion' => null, ':hcsolution' => null, ':userid' => $user['id']))) {
+                $errors[] = _('Could not update user status.').' '
+                            .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
+              }
+              $user['status'] = 'unverified';
+              $utils->log('user_checked', 'user: '.$user['id'].', email: '.$user['email']);
+            }
+            else {
+              $errors[] = _('Solution was not correct. Please start over.');
+              $utils->log('user_check_failed', 'user: '.$user['id'].', email: '.$user['email']);
+            }
+          }
+          if ($user['status'] == 'unchecked') {
+            // Display a humanity check.
+            $pagetype = 'human_check';
+            // simple numbers, we stay within the 0 to 100 range
+            $num1 = mt_rand(0, 10);
+            $num2 = mt_rand($num1, 100);
+            $operation = mt_rand(0, 1); // 0 is addition, 1 is subtraction
+            if ($operation == 0) {
+              $user['hcheck_question'] = sprintf(_('%s plus %s equals'), ($num2 - $num1), $num1);
+              $user['hcheck_solution'] = $num2;
+            }
+            else {
+              $user['hcheck_question'] = sprintf(_('%s minus %s equals'), $num2, $num1);
+              $user['hcheck_solution'] = $num2 - $num1;
+            }
+            $result = $db->prepare('UPDATE `auth_users` SET `hcheck_question` = :hcquestion, `hcheck_solution` = :hcsolution WHERE `id` = :userid;');
+            if (!$result->execute(array(':hcquestion' => $user['hcheck_question'], ':hcsolution' => $user['hcheck_solution'], ':userid' => $user['id']))) {
+              $errors[] = _('Could not generate check for being a human.').' '
+                          .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
+            }
+          }
+          elseif ($user['status'] == 'unverified') {
             // Send email for verification and show message to point to it.
             $mail = new email();
             $mail->setCharset('utf-8');
             $mail->addHeader('X-KAIRO-AUTH', 'email_verification');
             $mail->addRecipient($user['email']);
-            $mail->setSender('noreply@auth.kairo.at', _('KaiRo.at Authentication Service'));
-            $mail->setSubject('Email Verification for KaiRo.at Authentication');
+            $mail->setSender($utils->settings['info_from_email'], sprintf(_('%s Authentication Service'), $utils->settings['operator_name']));
+            $mail->setSubject(sprintf(_('Email Verification for %s Authentication'), $utils->settings['operator_name']));
             $mail->addMailText(_('Welcome!')."\n\n");
             $mail->addMailText(sprintf(_('This email address, %s, has been used for registration on "%s".'),
-                                      $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
+                                       $user['email'], sprintf(_('%s Authentication Service'), $utils->settings['operator_name']))."\n\n");
             $mail->addMailText(_('Please confirm that registration by clicking the following link (or calling it up in your browser):')."\n");
             $mail->addMailText($utils->getDomainBaseURL().strstr($_SERVER['REQUEST_URI'], '?', true)
                               .'?email='.rawurlencode($user['email']).'&verification_code='.rawurlencode($user['verify_hash'])."\n\n");
             $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");
             $mail->addMailText(_('Those websites will get to know your email address but not your password, which we store securely.')."\n");
             $mail->addMailText(_('If you do not call this confirmation link within 72 hours, your data will be deleted from our database.')."\n\n");
-            $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at'));
+            $mail->addMailText(sprintf(_('The %s team'), $utils->settings['operator_name']));
             //$mail->setDebugAddress("robert@localhost");
             $mailsent = $mail->send();
             if ($mailsent) {
@@ -138,7 +167,8 @@ if (!count($errors)) {
             }
             else {
               $utils->log('verify_mail_failure', 'user: '.$user['id'].', email: '.$user['email']);
-              $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.');
+              $errors[] = _('The confirmation email could not be sent to you.').' '
+                          .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
             }
           }
           else {
@@ -147,7 +177,8 @@ if (!count($errors)) {
             $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = :vcode WHERE `id` = :userid;');
             if (!$result->execute(array(':vcode' => $vcode, ':userid' => $user['id']))) {
               $utils->log('vhash_set_failure', 'user: '.$user['id']);
-              $errors[] = _('Could not initiate reset request. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
+              $errors[] = _('Could not initiate reset request.').' '
+                          .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
             }
             else {
               $utils->log('pwd_reset_request', 'user: '.$user['id'].', email: '.$user['email']);
@@ -157,16 +188,16 @@ if (!count($errors)) {
               $mail->setCharset('utf-8');
               $mail->addHeader('X-KAIRO-AUTH', 'password_reset');
               $mail->addRecipient($user['email']);
-              $mail->setSender('noreply@auth.kairo.at', _('KaiRo.at Authentication Service'));
-              $mail->setSubject('How to reset your password for KaiRo.at Authentication');
+              $mail->setSender($utils->settings['info_from_email'], sprintf(_('%s Authentication Service'), $utils->settings['operator_name']));
+              $mail->setSubject(sprintf(_('How to reset your password for %s Authentication'), $utils->settings['operator_name']));
               $mail->addMailText(_('Hi,')."\n\n");
               $mail->addMailText(sprintf(_('A request for setting a new password for this email address, %s, has been submitted on "%s".'),
-                                        $user['email'], _('KaiRo.at Authentication Service'))."\n\n");
+                                         $user['email'], sprintf(_('%s Authentication Service'), $utils->settings['operator_name']))."\n\n");
               $mail->addMailText(_('You can set a new password by clicking the following link (or calling it up in your browser):')."\n");
               $mail->addMailText($utils->getDomainBaseURL().strstr($_SERVER['REQUEST_URI'], '?', true)
                                 .'?email='.rawurlencode($user['email']).'&reset_code='.rawurlencode($resetcode)."\n\n");
               $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");
-              $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at'));
+              $mail->addMailText(sprintf(_('The %s team'), $utils->settings['operator_name']));
               //$mail->setDebugAddress("robert@localhost");
               $mailsent = $mail->send();
               if ($mailsent) {
@@ -174,7 +205,8 @@ if (!count($errors)) {
               }
               else {
                 $utils->log('pwd_reset_mail_failure', 'user: '.$user['id'].', email: '.$user['email']);
-                $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.');
+                $errors[] = _('The email with password reset instructions could not be sent to you.').' '
+                            .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
               }
             }
           }
@@ -212,7 +244,7 @@ if (!count($errors)) {
   }
   elseif (array_key_exists('reset', $_GET)) {
     if ($session['logged_in']) {
-      $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
+      $result = $db->prepare('SELECT `id`,`email`,`group_id` FROM `auth_users` WHERE `id` = :userid;');
       $result->execute(array(':userid' => $session['user']));
       $user = $result->fetch(PDO::FETCH_ASSOC);
       if (!$user['id']) {
@@ -226,14 +258,15 @@ if (!count($errors)) {
     }
   }
   elseif (array_key_exists('verification_code', $_GET)) {
-    $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `email` = :email AND `status` = \'unverified\' AND `verify_hash` = :vcode;');
+    $result = $db->prepare('SELECT `id`,`email`,`group_id` FROM `auth_users` WHERE `email` = :email AND `status` = \'unverified\' AND `verify_hash` = :vcode;');
     $result->execute(array(':email' => @$_GET['email'], ':vcode' => $_GET['verification_code']));
     $user = $result->fetch(PDO::FETCH_ASSOC);
     if ($user['id']) {
       $result = $db->prepare('UPDATE `auth_users` SET `verify_hash` = \'\', `status` = \'ok\' WHERE `id` = :userid;');
       if (!$result->execute(array(':userid' => $user['id']))) {
         $utils->log('verification_save_failure', 'user: '.$user['id']);
-        $errors[] = _('Could not save confirmation. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
+        $errors[] = _('Could not save confirmation.').' '
+                    .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
       }
       $pagetype = 'verification_done';
     }
@@ -243,7 +276,7 @@ if (!count($errors)) {
   }
   elseif (array_key_exists('reset_code', $_GET)) {
     $reset_fail = true;
-    $result = $db->prepare('SELECT `id`,`email`,`verify_hash` FROM `auth_users` WHERE `email` = :email');
+    $result = $db->prepare('SELECT `id`,`email`,`verify_hash`,`group_id` FROM `auth_users` WHERE `email` = :email');
     $result->execute(array(':email' => @$_GET['email']));
     $user = $result->fetch(PDO::FETCH_ASSOC);
     if ($user['id']) {
@@ -278,7 +311,7 @@ if (!count($errors)) {
     }
   }
   elseif (array_key_exists('clients', $_GET)) {
-    $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
+    $result = $db->prepare('SELECT `id`,`email`,`group_id` FROM `auth_users` WHERE `id` = :userid;');
     $result->execute(array(':userid' => $session['user']));
     $user = $result->fetch(PDO::FETCH_ASSOC);
     if ($session['logged_in'] && $user['id']) {
@@ -294,7 +327,8 @@ if (!count($errors)) {
                                     ':scope' => $scope,
                                     ':userid' => $user['id']))) {
           $utils->log('client_save_failure', 'client: '.$clientid);
-          $errors[] = 'Unexpectedly failed to save new client information. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.';
+          $errors[] = _('Unexpectedly failed to save new client information.').' '
+                      .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
         }
       }
       if (!count($errors)) {
@@ -337,7 +371,8 @@ if (!count($errors)) {
         $result = $db->prepare('UPDATE `auth_users` SET `pwdhash` = :pwdhash, `verify_hash` = \'\' WHERE `id` = :userid;');
         if (!$result->execute(array(':pwdhash' => $newHash, ':userid' => $session['user']))) {
           $utils->log('pwd_reset_failure', 'user: '.$session['user']);
-          $errors[] = _('Password reset failed. Please <a href="https://www.kairo.at/contact">contact KaiRo.at</a> and tell the team about this.');
+          $errors[] = _('Password reset failed.').' '
+                      .sprintf(_('Please <a href="%s">contact %s</a> and tell the team about this.'), $utils->settings['operator_contact_url'], $utils->settings['operator_name']);
         }
         else {
           $pagetype = 'reset_done';
@@ -351,7 +386,29 @@ if (!count($errors)) {
 }
 
 if (!count($errors)) {
-  if ($pagetype == 'verification_sent') {
+  if ($pagetype == 'human_check') {
+    $para = $body->appendElement('p', _('This is a new registration, please verify that you are a human by solving the calculation below.'));
+    $para->setAttribute('class', 'humancheckinfo');
+    $form = $body->appendForm('./', 'POST', 'humancheckform');
+    $form->setAttribute('id', 'humancheckform');
+    $ulist = $form->appendElement('ul');
+    $ulist->setAttribute('class', 'flat humancheck');
+    $litem = $ulist->appendElement('li');
+    $litem->setAttribute('class', 'donotshow');
+    $inptxt = $litem->appendInputEmail('email', 30, 20, 'login_email', $user['email']);
+    $inptxt->setAttribute('autocomplete', 'email');
+    $inptxt->setAttribute('placeholder', _('Email'));
+    $litem = $ulist->appendElement('li');
+    $litem->appendText($user['hcheck_question'].' ');
+    $inptxt = $litem->appendInputText('hcheck_solution', 20, 10, 'hcheck_solution');
+    $litem = $ulist->appendElement('li');
+    $litem->appendInputHidden('tcode', $utils->createTimeCode($session));
+    $submit = $litem->appendInputSubmit(_('Continue Registration'));
+    $para = $form->appendElement('p');
+    $para->setAttribute('class', 'toplink small');
+    $link = $para->appendLink('./', _('Cancel'));
+  }
+  elseif ($pagetype == 'verification_sent') {
     $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']));
     $para->setAttribute('class', 'verifyinfo pending');
     $para = $body->appendElement('p', _('Reload this page after you confirm to continue.'));
@@ -479,7 +536,7 @@ if (!count($errors)) {
     $link = $litem->appendLink('./?logout', _('Log out'));
     $litem = $ulist->appendElement('li');
     $link = $litem->appendLink('./?addemail', _('Add another email address'));
-    if (in_array($user['email'], $utils->client_reg_email_whitelist)) {
+    if (($utils->client_reg_email_whitelist === false) || (in_array($user['email'], $utils->client_reg_email_whitelist))) {
       $litem = $ulist->appendElement('li');
       $link = $litem->appendLink('./?clients', _('Manage OAuth2 clients'));
     }
@@ -512,7 +569,8 @@ if (count($errors)) {
   $list = $body->appendElement('ul');
   $list->setAttribute('class', 'flat warn');
   foreach ($errors as $msg) {
-    $item = $list->appendElement('li', $msg);
+    $item = $list->appendElement('li');
+    $item->appendHTMLMarkup($msg);
   }
   $body->appendButton(_('Back'), 'history.back();');
 }