UserClaimsNormalizer.php in Simple OAuth (OAuth2) & OpenID Connect 5.x
File
src/Normalizer/UserClaimsNormalizer.php
View source
<?php
namespace Drupal\simple_oauth\Normalizer;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\serialization\Normalizer\NormalizerBase;
use Drupal\simple_oauth\Entities\UserEntityWithClaims;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class UserClaimsNormalizer extends NormalizerBase implements NormalizerInterface {
protected $supportedInterfaceOrClass = UserEntityWithClaims::class;
protected $format = 'json';
protected $userStorage;
protected $claims;
protected $moduleHandler;
public function __construct(EntityTypeManagerInterface $entity_type_manager, array $claims, ModuleHandlerInterface $module_handler) {
$this->userStorage = $entity_type_manager
->getStorage('user');
$this->claims = $claims;
$this->moduleHandler = $module_handler;
}
public function normalize($user_entity, $format = NULL, array $context = []) {
assert($user_entity instanceof UserEntityWithClaims);
$identifier = $user_entity
->getIdentifier();
$account = $context[$identifier] instanceof AccountInterface ? $context[$identifier] : $this->userStorage
->load($identifier);
assert($account instanceof AccountInterface);
return $this
->getClaimsFromAccount($account);
}
private function getClaimsFromAccount(AccountInterface $account) {
$profile_url = $account
->toUrl('canonical', [
'absolute' => TRUE,
])
->toString();
$claim_values = [
'sub' => $account
->id(),
'name' => $account
->getDisplayName(),
'preferred_username' => $account
->getAccountName(),
'email' => $account
->getEmail(),
'email_verified' => TRUE,
'profile' => $profile_url,
'locale' => $account
->getPreferredLangcode(),
'zoneinfo' => $account
->getTimeZone(),
];
if ($account instanceof EntityChangedInterface) {
$claim_values['updated_at'] = $account
->getChangedTime();
}
$context = [
'account' => $account,
'claims' => $this->claims,
];
$this->moduleHandler
->alter('simple_oauth_oidc_claims', $claim_values, $context);
return array_intersect_key($claim_values, array_flip($this->claims));
}
}