You are here

public function DrupalUserProcessor::ldapAssociateDrupalAccount in Lightweight Directory Access Protocol (LDAP) 8.4

Same name and namespace in other branches
  1. 8.3 ldap_user/src/Processor/DrupalUserProcessor.php \Drupal\ldap_user\Processor\DrupalUserProcessor::ldapAssociateDrupalAccount()

Set LDAP associations of a Drupal account by altering user fields.

Parameters

string $drupal_username: The Drupal username.

Return value

bool Returns FALSE on invalid user or LDAP accounts.

File

ldap_user/src/Processor/DrupalUserProcessor.php, line 275

Class

DrupalUserProcessor
Handles processing of a user from LDAP to Drupal.

Namespace

Drupal\ldap_user\Processor

Code

public function ldapAssociateDrupalAccount(string $drupal_username) : bool {
  if (!$this->config
    ->get('drupalAcctProvisionServer')) {
    return FALSE;
  }

  /** @var \Drupal\ldap_servers\Entity\Server $ldap_server */
  $ldap_server = $this->entityTypeManager
    ->getStorage('ldap_server')
    ->load($this->config
    ->get('drupalAcctProvisionServer'));
  $load_by_name = $this->entityTypeManager
    ->getStorage('user')
    ->loadByProperties([
    'name' => $drupal_username,
  ]);
  if (!$load_by_name) {
    $this->logger
      ->error('Failed to LDAP associate Drupal account %drupal_username because account not found', [
      '%drupal_username' => $drupal_username,
    ]);
    return FALSE;
  }
  $this->account = reset($load_by_name);
  $this->ldapEntry = $this->ldapUserManager
    ->matchUsernameToExistingLdapEntry($drupal_username);
  if (!$this->ldapEntry) {
    $this->logger
      ->error('Failed to LDAP associate Drupal account %drupal_username because corresponding LDAP entry not found', [
      '%drupal_username' => $drupal_username,
    ]);
    return FALSE;
  }
  $persistent_uid = $ldap_server
    ->derivePuidFromLdapResponse($this->ldapEntry);
  if (!empty($persistent_uid)) {
    $this->account
      ->set('ldap_user_puid', $persistent_uid);
  }
  $this->account
    ->set('ldap_user_puid_property', $ldap_server
    ->getUniquePersistentAttribute());
  $this->account
    ->set('ldap_user_puid_sid', $ldap_server
    ->id());
  $this->account
    ->set('ldap_user_current_dn', $this->ldapEntry
    ->getDn());
  $this->account
    ->set('ldap_user_last_checked', time());
  $this->account
    ->set('ldap_user_ldap_exclude', 0);
  $this
    ->saveAccount();
  $this->externalAuth
    ->save($this->account, 'ldap_user', $this->account
    ->getAccountName());
  return TRUE;
}