You are here

public function LdapProtectedUserFieldConstraintValidator::validate in Lightweight Directory Access Protocol (LDAP) 8.4

Overrides ProtectedUserFieldConstraintValidator::validate

File

ldap_user/src/Plugin/Validation/Constraint/LdapProtectedUserFieldConstraintValidator.php, line 47

Class

LdapProtectedUserFieldConstraintValidator
Validates the LdapProtectedUserFieldConstraint constraint.

Namespace

Drupal\ldap_user\Plugin\Validation\Constraint

Code

public function validate($items, Constraint $constraint) : void {
  if (!isset($items)) {
    return;
  }

  /** @var \Drupal\Core\Field\FieldItemListInterface $items */
  $field = $items
    ->getFieldDefinition();

  /** @var \Drupal\user\UserInterface $account */
  $account = $items
    ->getEntity();
  if (!isset($account) || !empty($account->_skipProtectedUserFieldConstraint)) {

    // Looks like we are validating a field not being part of a user, or the
    // constraint should be skipped, so do nothing.
    return;
  }

  // Only validate for existing entities and if this is the current user.
  if ($account
    ->isNew() || $account
    ->id() != $this->currentUser
    ->id()) {
    return;
  }

  // Special case for the password, it being empty means that the existing
  // password should not be changed, ignore empty password fields.
  $value = $items->value;
  if ($field
    ->getName() === 'pass' && !$value) {
    return;
  }

  /** @var \Drupal\user\UserInterface $account_unchanged */
  $account_unchanged = $this->userStorage
    ->loadUnchanged($account
    ->id());
  if ($items
    ->getValue() === $account_unchanged
    ->get($field
    ->getName())
    ->getValue()) {
    return;
  }

  // We need the password, the existing one should be here.
  CredentialsStorage::storeUserPassword($account
    ->get('pass')->existing);
  $credentialsAuthenticationResult = $this->loginValidator
    ->validateCredentialsLoggedIn($account_unchanged);
  if ($credentialsAuthenticationResult === $this->loginValidator::AUTHENTICATION_SUCCESS) {

    // Directory approved the request, existing password matches.
    return;
  }
  parent::validate($items, $constraint);
}