You are here

public function ScopeRepository::finalizeScopes in Simple OAuth (OAuth2) & OpenID Connect 8.2

Same name and namespace in other branches
  1. 8.4 src/Repositories/ScopeRepository.php \Drupal\simple_oauth\Repositories\ScopeRepository::finalizeScopes()
  2. 8.3 src/Repositories/ScopeRepository.php \Drupal\simple_oauth\Repositories\ScopeRepository::finalizeScopes()
  3. 5.x 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 49

Class

ScopeRepository

Namespace

Drupal\simple_oauth\Repositories

Code

public function finalizeScopes(array $scopes, $grant_type, ClientEntityInterface $client_entity, $user_identifier = NULL) {

  /** @var \Drupal\user\UserInterface $user */
  $user = $user_identifier ? $this->entityTypeManager
    ->getStorage('user')
    ->load($user_identifier) : $client_entity
    ->getDrupalEntity()
    ->getDefaultUser();
  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\simple_oauth\Entity\Oauth2ClientInterface $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;
}