You are here

public function ScopeRepository::finalizeScopes in Simple OAuth (OAuth2) & OpenID Connect 5.x

Same name and namespace in other branches
  1. 8.4 src/Repositories/ScopeRepository.php \Drupal\simple_oauth\Repositories\ScopeRepository::finalizeScopes()
  2. 8.2 src/Repositories/ScopeRepository.php \Drupal\simple_oauth\Repositories\ScopeRepository::finalizeScopes()
  3. 8.3 src/Repositories/ScopeRepository.php \Drupal\simple_oauth\Repositories\ScopeRepository::finalizeScopes()

This will remove any role that is not associated to the identified user and add all the roles configured in the client.

File

src/Repositories/ScopeRepository.php, line 54

Class

ScopeRepository
The repository for scopes.

Namespace

Drupal\simple_oauth\Repositories

Code

public function finalizeScopes(array $scopes, $grant_type, ClientEntityInterface $client_entity, $user_identifier = NULL) {
  $default_user = NULL;
  try {
    $default_user = $client_entity
      ->getDrupalEntity()
      ->get('user_id')->entity;
  } catch (\InvalidArgumentException $e) {

    // Do nothing.
  }

  /** @var \Drupal\user\UserInterface $user */
  $user = $user_identifier ? $this->entityTypeManager
    ->getStorage('user')
    ->load($user_identifier) : $default_user;
  if (!$user) {
    return [];
  }
  $role_ids = $user
    ->getRoles();

  // Given a user, only allow the roles that the user already has, regardless
  // of what has been requested.
  $scopes = array_filter($scopes, function (ScopeEntityInterface $scope) use ($role_ids) {
    return in_array($scope
      ->getIdentifier(), $role_ids);
  });

  // Make sure that the Authenticated role is added as well.
  $scopes = $this
    ->addRoleToScopes($scopes, RoleInterface::AUTHENTICATED_ID);

  // Make sure that the client roles are added to the scopes as well.

  /** @var \Drupal\consumers\Entity\Consumer $client_drupal_entity */
  $client_drupal_entity = $client_entity
    ->getDrupalEntity();
  $scopes = array_reduce($client_drupal_entity
    ->get('roles')
    ->getValue(), function ($scopes, $role_id) {
    return $this
      ->addRoleToScopes($scopes, $role_id['target_id']);
  }, $scopes);
  return $scopes;
}