You are here

public function SimplesamlphpDrupalAuth::roleMatchSync in simpleSAMLphp Authentication 8.3

Synchronizes (adds/removes) user account roles.

Parameters

\Drupal\user\UserInterface $account: The Drupal user to sync roles for.

1 call to SimplesamlphpDrupalAuth::roleMatchSync()
SimplesamlphpDrupalAuth::externalLoginRegister in src/Service/SimplesamlphpDrupalAuth.php
Log in and optionally register a user based on the authname provided.

File

src/Service/SimplesamlphpDrupalAuth.php, line 295

Class

SimplesamlphpDrupalAuth
Service to link SimpleSAMLphp authentication with Drupal users.

Namespace

Drupal\simplesamlphp_auth\Service

Code

public function roleMatchSync(UserInterface $account) {

  // Get matching roles based on retrieved SimpleSAMLphp attributes.
  $matching_roles = $this
    ->getMatchingRoles();

  // Get user's current roles, excluding locked roles (e.g. Authenticated).
  $current_roles = $account
    ->getRoles(TRUE);

  // Set boolean to only update account when needed.
  $account_updated = FALSE;

  // Remove non-locked roles not mapped to the user via SAML.
  foreach (array_diff($current_roles, $matching_roles) as $role_id) {
    if ($this->config
      ->get('debug')) {
      $this->logger
        ->debug('Removing role %role from user %name', [
        '%role' => $role_id,
        '%name' => $account
          ->getAccountName(),
      ]);
    }
    $account
      ->removeRole($role_id);
    $account_updated = TRUE;
  }

  // Add roles mapped to the user via SAML.
  foreach (array_diff($matching_roles, $current_roles) as $role_id) {
    if ($this->config
      ->get('debug')) {
      $this->logger
        ->debug('Adding role %role to user %name', [
        '%role' => $role_id,
        '%name' => $account
          ->getAccountName(),
      ]);
    }
    $account
      ->addRole($role_id);
    $account_updated = TRUE;
  }
  if ($account_updated) {
    $account
      ->save();
  }
}