PasswordUsername.php in Password Policy 8.3
File
password_policy_username/src/Plugin/PasswordConstraint/PasswordUsername.php
View source
<?php
namespace Drupal\password_policy_username\Plugin\PasswordConstraint;
use Drupal\Core\Form\FormStateInterface;
use Drupal\password_policy\PasswordConstraintBase;
use Drupal\password_policy\PasswordPolicyValidation;
use Drupal\user\UserInterface;
class PasswordUsername extends PasswordConstraintBase {
public function validate($password, UserInterface $user) {
$config = $this
->getConfiguration();
$validation = new PasswordPolicyValidation();
if ($config['disallow_username'] && stripos($password, $user
->getAccountName()) !== FALSE) {
$validation
->setErrorMessage($this
->t('Password must not contain the username.'));
}
return $validation;
}
public function defaultConfiguration() {
return [
'disallow_username' => TRUE,
];
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$config = $this
->getConfiguration();
$form['disallow_username'] = [
'#type' => 'hidden',
'#value' => $config['disallow_username'],
];
$form['disallow_username_message'] = [
'#type' => 'description',
'#markup' => $this
->t('Prevent user from having a password containing their username.'),
];
return $form;
}
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['disallow_username'] = $form_state
->getValue('disallow_username');
}
public function getSummary() {
return $this
->t("Password must not contain the user's username.");
}
}