PasswordStrength.php in Password Strength 8.2
File
src/Plugin/PasswordConstraint/PasswordStrength.php
View source
<?php
namespace Drupal\password_strength\Plugin\PasswordConstraint;
use Drupal\Core\Form\FormStateInterface;
use Drupal\password_policy\PasswordConstraintBase;
use Drupal\password_policy\PasswordPolicyValidation;
use Drupal\user\UserInterface;
class PasswordStrength extends PasswordConstraintBase {
public $strength_scores = [
'0' => 'Very weak (0)',
'1' => 'Weak (1)',
'2' => 'Average (2)',
'3' => 'Strong (3)',
'4' => 'Very strong (4)',
];
function validate($password, UserInterface $user) {
$userData = array_merge($user
->getAccountName() ? [
$user
->getAccountName(),
] : [], $user
->getEmail() ? [
$user
->getEmail(),
] : []);
$configuration = $this
->getConfiguration();
$validation = new PasswordPolicyValidation();
$password_strength = new \Drupal\password_strength\PasswordStrength();
$strength = $password_strength
->passwordStrength($password, $userData);
if ($strength['score'] < $configuration['strength_score']) {
$validation
->setErrorMessage($this
->t('The password has a score of @password-score but the policy requires a score of at least @policy-score', array(
'@password-score' => $strength['score'],
'@policy-score' => $configuration['strength_score'],
)));
}
return $validation;
}
public function defaultConfiguration() {
return [
'strength_score' => 3,
];
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['strength_score'] = array(
'#type' => 'select',
'#title' => t('Password Strength Minimum Score'),
'#options' => $this->strength_scores,
'#default_value' => $this
->getConfiguration()['strength_score'],
);
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['strength_score'] = $form_state
->getValue('strength_score');
}
public function getSummary() {
return $this
->t('Password Strength minimum score of @score', array(
'@score' => $this->configuration['strength_score'],
));
}
}