Commit 34e72dab authored by Marcelo Vani's avatar Marcelo Vani
Browse files

Issue #3166935: Making Captcha Keypad compatible with Captcha.

parent 80aaccb9
Loading
Loading
Loading
Loading
+1 −0
Changes for Makefile: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -18,6 +18,7 @@ build-local-8:
build-local-9:
	docker run --rm --name drupalci_${PROJECT_NAME} \
	    -v ${PWD}/:/var/www/html/web/modules/contrib/${PROJECT_NAME} \
	    -v ${PWD}/../modules/:/var/www/html/web/modules \
	    -v ~/artifacts:/artifacts \
	    -p ${PROJECT_PORT}:80 \
	    -d marcelovani/drupalci:9-apache-interactive
+66 −82
Changes for captcha_keypad.module: 66 added lines, 82 removed lines.
Original line number Diff line number Diff line
@@ -5,6 +5,7 @@
 * Captcha keypad module.
 */

use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;

@@ -36,67 +37,10 @@ function captcha_keypad_form_alter(&$form, FormStateInterface $form_state, $form
    return;
  }

  $digits = \Drupal::config('captcha_keypad.settings')->get('captcha_keypad_code_size');
  $input = $form_state->getUserInput();
  if (!isset($input['captcha_keypad_hidden'])) {
    $code = _captcha_keypad_get_code($digits);
  }
  else {
    $code = $input['captcha_keypad_hidden'];
  }

  $form['captcha_keypad'] = [
    '#title' => t('Security'),
    '#type' => 'fieldset',
    '#attributes' => ['class' => ['captcha-keypad-wrapper', 'captcha-keypad-' . $code]],
    '#weight' => (isset($form['actions']['#weight']) ? $form['actions']['#weight'] - 1 : 99.5),
  ];

  $form['captcha_keypad']['captcha_keypad_input'] = [
    '#title' => t('Code'),
    '#type' => 'textfield',
    '#attributes' => ['class' => ['captcha-keypad-input']],
    '#size' => $digits,
    '#required' => TRUE,
  ];

  $form['captcha_keypad']['captcha_keypad_hidden'] = [
    '#type' => 'hidden',
    '#size' => 1,
    '#value' => $code,
  ];

  $form['captcha_keypad']['captcha_keypad_keypad_used'] = [
    '#type' => 'hidden',
    '#size' => 1,
    '#attributes' => ['class' => ['captcha-keypad-keypad-used']],
    '#default_value' => '',
  ];

  $keypad = '';
  $keys = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  if (\Drupal::config('captcha_keypad.settings')->get('captcha_keypad_shuffle_keypad')) {
    shuffle($keys);
  }
  for ($n = 0; $n <= 8; $n++) {
    $keypad .= '<span>' . $keys[$n] . '</span>';
  }
  $form['captcha_keypad']['keypad'] = [
    '#prefix' => '<span class="captcha-keypad"><span class="inner">',
    '#markup' => $keypad,
    '#suffix' => '</span></span>',
  ];

  $form['captcha_keypad']['code'] = [
    '#prefix' => '<span class="sequence">',
    '#markup' => t('Click/tap this sequence: <strong>:code</strong>', [':code' => $code]),
    '#suffix' => '</span>',
  ];
  $form = \Drupal::service('captcha_keypad.controller')->getForm($form);

  array_unshift($form['#validate'], 'captcha_keypad_form_validate');

  $form['#attached']['library'][] = 'captcha_keypad/captcha_keypad';

  // Rebuild form.
  $form_state->setRebuild();
}
@@ -105,41 +49,81 @@ function captcha_keypad_form_alter(&$form, FormStateInterface $form_state, $form
 * Callback function for form submit.
 */
function captcha_keypad_form_validate(array &$form, FormStateInterface $form_state) {
  $captcha_keypad_input = $captcha_keypad_hidden = $captcha_keypad_keypad_used = '';
  $input = $form_state->getUserInput();
  foreach (['input', 'hidden', 'keypad_used'] as $i) {
    $v = "captcha_keypad_$i";
    $$v = isset($input[$v]) ? $input[$v] : '';
  \Drupal::service('captcha_keypad.controller')->validateForm($form_state);
}

  // For Functional tests to work.
  $digits = \Drupal::config('captcha_keypad.settings')->get('captcha_keypad_code_size');
  if ($digits == 99 && $captcha_keypad_input == 'testing') {
    $captcha_keypad_keypad_used = 'Yes';
    $captcha_keypad_hidden = $captcha_keypad_input;
/**
 * Implements hook_page_attachments().
 */
function captcha_keypad_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'captcha_keypad/captcha_keypad';
}

  if ($captcha_keypad_input != $captcha_keypad_hidden || $captcha_keypad_keypad_used != 'Yes') {
    $form_state->setErrorByName('captcha_keypad_input', t('Invalid security code.'));
/**
 * Implements hook_captcha().
 */
function captcha_keypad_captcha($op, $captcha_type = '') {
  // @todo add tests for captcha + keypad
  switch ($op) {
    case 'list':
      return ['Keypad'];

    case 'generate':
      if ($captcha_type == 'Keypad') {
        // Captcha doesn't play well with Drupal\Core\Form\FormBuilder, so we are using a custom form controller.
        $form = \Drupal::service('captcha_keypad.controller')->getForm();

        return [
          'form' => $form['captcha_keypad'],
          'solution' => $form['captcha_keypad']['captcha_keypad_hidden']['#value'],
          'captcha_validate' => 'captcha_keypad_captcha_validate',
        ];
      }
      elseif ($captcha_type == 'Test') {
        // @todo finish this
        // This challenge is not visible through the administrative interface
        // as it is not listed in captcha_captcha('list'),
        // but it is meant for debugging and testing purposes.
        // TODO for Drupal 7 version: This should be done with a mock module,
        // but Drupal 6 does not support this (mock modules can not be hidden).
//        $result = [
//          'solution' => 'Test 123',
//          'form' => [],
//        ];
//        $result['form']['captcha_response'] = [
//          '#type' => 'textfield',
//          '#title' => t('Test one two three'),
//          '#required' => TRUE,
//          '#cache' => ['max-age' => 0],
//        ];
//        \Drupal::service('page_cache_kill_switch')->trigger();
//
//        return $result;
      }
      break;
  }
}

/**
 * Helper to generate the code.
 * Validate callback for Captcha module.
 *
 * @param $solution
 * @param $captcha_response
 * @param $element
 * @param $form_state
 *
 * @return boolean
 *  TRUE/FALSE depending on response.
 */
function _captcha_keypad_get_code($digits) {
  // Little trick to allow testing.
  if ($digits == '99') {
    return 'testing';
function captcha_keypad_captcha_validate($solution, $captcha_response, $element, $form_state) {
  if ($solution !== $captcha_response) {
    return FALSE;
  }

  // Limit size.
  if ($digits > 16) {
    $digits = 16;
  $input = $form_state->getUserInput();
  if ($input['captcha_keypad_keypad_used'] !== '1') {
    return FALSE;
  }

  $code = rand(pow(10, $digits - 1), pow(10, $digits) - 1);
  $code = str_replace('0', '1', $code . '');

  return $code;
  return TRUE;
}
+4 −0
Changes for captcha_keypad.services.yml: 4 added lines, 0 removed lines.
Original line number Diff line number Diff line
services:
  captcha_keypad.controller:
    class: Drupal\captcha_keypad\Controller\CaptchaKeypad
    arguments: ['@config.factory']
+1 −1
Changes for css/captcha_keypad.css: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -34,6 +34,6 @@
  height: auto;
}

#edit-captcha-keypad-input {
#edit-captcha-response {
  max-width: 70px;
}
+7 −7
Changes for js/captcha_keypad.js: 7 added lines, 7 removed lines.
Original line number Diff line number Diff line
@@ -3,20 +3,20 @@
    attach: function (context, settings) {
      var clear = '<span class="clear">' + Drupal.t('Clear') + '</span><br/>' + '<span class="message"></span>';
      $('.captcha-keypad-wrapper', context).once('captcha-keypad').each(function() {
        $(this).find('.form-item-captcha-keypad-input').append(clear);
        $(this).find('.form-item-captcha-response').append(clear);
        $(this).find('.captcha-keypad-keypad-used').val('');
        $(this).find('.captcha-keypad-input').val('').keyup(function () {
          $(this).parent().find('.captcha-keypad-input').val('');
        $(this).find('.captcha-response').val('').keyup(function () {
          $(this).parent().find('.captcha-response').val('');
          $(this).parent().find('.message').css('color', 'red').html(Drupal.t('Use keypad ->'));
        });
        $(this).find('.form-item-captcha-keypad-input .clear').click(function () {
          $(this).parent().find('.captcha-keypad-input').val('');
        $(this).find('.form-item-captcha-response .clear').click(function () {
          $(this).parent().find('.captcha-response').val('');
          $(this).parent().find('.message').html('');
        });
        $(this).find('.captcha-keypad .inner span').click(function () {
          $(this).parent().parent().parent().find('.captcha-keypad-keypad-used').val('Yes');
          $(this).parent().parent().parent().find('.captcha-keypad-keypad-used').val('1');
          $(this).parent().parent().parent().find('.message').html('');
          var input = $(this).parent().parent().parent().find('.captcha-keypad-input');
          var input = $(this).parent().parent().parent().find('.captcha-response');
          input.val(input.val() + $(this).text());
        });
      });
Loading