ConsecutiveCharacters.php in Password Policy 8.3
File
password_policy_consecutive/src/Plugin/PasswordConstraint/ConsecutiveCharacters.php
View source
<?php
namespace Drupal\password_policy_consecutive\Plugin\PasswordConstraint;
use Drupal\Core\Form\FormStateInterface;
use Drupal\password_policy\PasswordConstraintBase;
use Drupal\password_policy\PasswordPolicyValidation;
use Drupal\user\UserInterface;
class ConsecutiveCharacters extends PasswordConstraintBase {
public function validate($password, UserInterface $user) {
$validation = new PasswordPolicyValidation();
$max = $this
->getConfiguration()['max_consecutive_characters'];
if ($max < 2) {
$validation
->setErrorMessage($this
->t('Invalid plugin configuration.'));
}
$pattern = '/(.)\\1{' . ($max - 1) . '}/';
if (preg_match($pattern, $password)) {
$validation
->setErrorMessage($this
->t('Password must have fewer than @max consecutive identical characters. This is case sensitive.', [
'@max' => $max,
]));
}
return $validation;
}
public function defaultConfiguration() {
return [
'max_consecutive_characters' => 2,
];
}
public function getSummary() {
return $this
->t('Maximum consecutive identical characters: @max', [
'@max' => $this
->getConfiguration()['max_consecutive_characters'],
]);
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$range = range(2, 5);
$form['max_consecutive_characters'] = [
'#type' => 'select',
'#options' => array_combine(array_values($range), $range),
'#title' => $this
->t('Maximum consecutive identical characters'),
'#description' => $this
->t('Select the maximum number of consecutive identical characters allowed in the password.'),
'#default_value' => $this
->getConfiguration()['max_consecutive_characters'],
];
return $form;
}
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
$types = $form_state
->getValue('max_consecutive_characters');
if (!is_numeric($types) || $types < 2) {
$form_state
->setErrorByName('max_consecutive_characters', $this
->t('The number of consecutive identical characters must be higher than 1 otherwise all passwords will fail.'));
}
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['max_consecutive_characters'] = $form_state
->getValue('max_consecutive_characters');
}
}