ScopeRepository.php in Simple OAuth (OAuth2) & OpenID Connect 8.3
File
src/Repositories/ScopeRepository.php
View source
<?php
namespace Drupal\simple_oauth\Repositories;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\user\RoleInterface;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use Drupal\simple_oauth\Entities\ScopeEntity;
class ScopeRepository implements ScopeRepositoryInterface {
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
public function getScopeEntityByIdentifier($scope_identifier) {
$role = $this->entityTypeManager
->getStorage('user_role')
->load($scope_identifier);
if (!$role) {
return NULL;
}
return $this
->scopeFactory($role);
}
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) {
}
$user = $user_identifier ? $this->entityTypeManager
->getStorage('user')
->load($user_identifier) : $default_user;
if (!$user) {
return [];
}
$role_ids = $user
->getRoles();
$scopes = array_filter($scopes, function (ScopeEntityInterface $scope) use ($role_ids) {
return in_array($scope
->getIdentifier(), $role_ids);
});
$scopes = $this
->addRoleToScopes($scopes, RoleInterface::AUTHENTICATED_ID);
$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;
}
protected function scopeFactory(RoleInterface $role) {
return new ScopeEntity($role);
}
protected function addRoleToScopes(array $scopes, $additional_role_id) {
$role_storage = $this->entityTypeManager
->getStorage('user_role');
$found = array_filter($scopes, function (ScopeEntityInterface $scope) use ($additional_role_id) {
return $scope
->getIdentifier() == $additional_role_id;
});
if (empty($found)) {
$additional_role = $role_storage
->load($additional_role_id);
array_push($scopes, $this
->scopeFactory($additional_role));
}
return $scopes;
}
}