You are here

public function EntryForm::validateForm in Two-factor Authentication (TFA) 8

Form validation handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormBase::validateForm

File

src/Form/EntryForm.php, line 219

Class

EntryForm
TFA entry form.

Namespace

Drupal\tfa\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state
    ->getValues();
  $window = $this->tfaSettings
    ->get('tfa_flood_window') ?: 300;
  $threshold = $this->tfaSettings
    ->get('tfa_flood_threshold') ?: 6;
  if ($this->tfaSettings
    ->get('tfa_flood_uid_only')) {

    // Register flood events based on the uid only, so they apply for any
    // IP address. This is the most secure option.
    $this->floodIdentifier = $values['account']
      ->id();
  }
  else {

    // The default identifier is a combination of uid and IP address. This
    // is less secure but more resistant to denial-of-service attacks that
    // could lock out all users with public user names.
    $this->floodIdentifier = $values['account']
      ->id() . '-' . $this
      ->getRequest()
      ->getClientIP();
  }

  // Flood control.
  if (!$this->flood
    ->isAllowed('tfa.failed_validation', $threshold, $window, $this->floodIdentifier)) {
    $form_state
      ->setErrorByName('', $this
      ->t('Failed validation limit reached. %limit wrong codes in @interval. Try again later.', [
      '%limit' => $threshold,
      '@interval' => $this->dateFormatter
        ->formatInterval($window),
    ]));
    return;
  }
  $validated = $this->tfaValidationPlugin
    ->validateForm($form, $form_state);
  if (!$validated) {

    // @todo Either define getErrorMessages in the TfaValidationInterface, or don't use it.
    // For now, let's just check that it exists before assuming.
    if (method_exists($this->tfaValidationPlugin, 'getErrorMessages')) {
      $form_state
        ->clearErrors();
      $errors = $this->tfaValidationPlugin
        ->getErrorMessages();
      $form_state
        ->setErrorByName(key($errors), current($errors));
    }
    $this->flood
      ->register('tfa.failed_validation', $this->tfaSettings
      ->get('tfa_flood_window'), $this->floodIdentifier);
  }
}