You are here

protected function AuthController::auth0UpdateRoles in Auth0 Single Sign On 8.2

Updates the $user->roles of a user based on the Auth0 role mappings.

Parameters

array $userInfo: The user info array.

\Drupal\user\Entity\User $user: The drupal user entity.

array $edit: The edit array.

1 call to AuthController::auth0UpdateRoles()
AuthController::auth0UpdateFieldsAndRoles in src/Controller/AuthController.php
Update the Auth fields.

File

src/Controller/AuthController.php, line 821
Contains \Drupal\auth0\Controller\AuthController.

Class

AuthController
Controller routines for auth0 authentication.

Namespace

Drupal\auth0\Controller

Code

protected function auth0UpdateRoles(array $userInfo, User $user, array &$edit) {
  $this->auth0Logger
    ->notice("Mapping Roles");
  $auth0_claim_to_use_for_role = $this->config
    ->get('auth0_claim_to_use_for_role');
  if (isset($auth0_claim_to_use_for_role) && !empty($auth0_claim_to_use_for_role)) {
    $claim_value = isset($userInfo[$auth0_claim_to_use_for_role]) ? $userInfo[$auth0_claim_to_use_for_role] : '';
    $this->auth0Logger
      ->notice('claim_value ' . print_r($claim_value, TRUE));
    $claim_values = [];
    if (is_array($claim_value)) {
      $claim_values = $claim_value;
    }
    else {
      $claim_values[] = $claim_value;
    }
    $auth0_role_mapping = $this->config
      ->get('auth0_role_mapping');
    $mappings = $this
      ->auth0PipeListToArray($auth0_role_mapping);
    $roles_granted = [];
    $roles_managed_by_mapping = [];
    foreach ($mappings as $mapping) {
      $this->auth0Logger
        ->notice('mapping ' . print_r($mapping, TRUE));
      $roles_managed_by_mapping[] = $mapping[1];
      if (in_array($mapping[0], $claim_values)) {
        $roles_granted[] = $mapping[1];
      }
    }
    $roles_granted = array_unique($roles_granted);
    $roles_managed_by_mapping = array_unique($roles_managed_by_mapping);
    $not_granted = array_diff($roles_managed_by_mapping, $roles_granted);
    $user_roles = $user
      ->getRoles();
    $new_user_roles = array_merge(array_diff($user_roles, $not_granted), $roles_granted);
    $roles_to_add = array_diff($new_user_roles, $user_roles);
    $roles_to_remove = array_diff($user_roles, $new_user_roles);
    if (empty($roles_to_add) && empty($roles_to_remove)) {
      $this->auth0Logger
        ->notice('no changes to roles detected');
      return;
    }
    $this->auth0Logger
      ->notice('changes to roles detected');
    $edit['roles'] = $new_user_roles;
    foreach ($roles_to_add as $new_role) {
      $user
        ->addRole($new_role);
    }
    foreach ($roles_to_remove as $remove_role) {
      $user
        ->removeRole($remove_role);
    }
  }
}