You are here

public function LtiToolProviderRolesEventSubscriber::onAuthenticated in LTI Tool Provider 2.x

Same name and namespace in other branches
  1. 8 modules/lti_tool_provider_roles/src/EventSubscriber/LtiToolProviderRolesEventSubscriber.php \Drupal\lti_tool_provider_roles\EventSubscriber\LtiToolProviderRolesEventSubscriber::onAuthenticated()

Parameters

LtiToolProviderAuthenticatedEvent $event:

File

modules/lti_tool_provider_roles/src/EventSubscriber/LtiToolProviderRolesEventSubscriber.php, line 52

Class

LtiToolProviderRolesEventSubscriber

Namespace

Drupal\lti_tool_provider_roles\EventSubscriber

Code

public function onAuthenticated(LtiToolProviderAuthenticatedEvent $event) {
  $mapped_roles = Drupal::config('lti_tool_provider_roles.settings')
    ->get('mapped_roles');
  $context = $event
    ->getContext();
  $user = $event
    ->getUser();
  $user_roles = user_roles(TRUE);
  $lti_roles = parse_roles($context['roles']);
  if ($user
    ->getDisplayName() === 'ltiuser') {
    return;
  }
  if (!$mapped_roles || !count($mapped_roles)) {
    return;
  }
  foreach ($mapped_roles as $user_role => $lti_role) {
    if (array_key_exists($user_role, $user_roles)) {
      if (in_array($lti_role, $lti_roles)) {
        $user
          ->addRole($user_role);
      }
      else {
        $user
          ->removeRole($user_role);
      }
    }
  }
  try {
    $rolesEvent = new LtiToolProviderRolesEvent($context, $user);
    LtiToolProviderEvent::dispatchEvent($this->eventDispatcher, $rolesEvent);
    if ($rolesEvent
      ->isCancelled()) {
      throw new Exception($event
        ->getMessage());
    }
    $user
      ->save();
  } catch (Exception $e) {
    Drupal::logger('lti_tool_provider_roles')
      ->error($e
      ->getMessage());
  }
}