RevocableTokenRepositoryTrait.php in Simple OAuth (OAuth2) & OpenID Connect 5.x
File
src/Repositories/RevocableTokenRepositoryTrait.php
View source
<?php
namespace Drupal\simple_oauth\Repositories;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
use Symfony\Component\Serializer\SerializerInterface;
trait RevocableTokenRepositoryTrait {
protected static $entityTypeId = 'oauth2_token';
protected $entityTypeManager;
protected $serializer;
public function __construct(EntityTypeManagerInterface $entity_type_manager, SerializerInterface $serializer) {
$this->entityTypeManager = $entity_type_manager;
$this->serializer = $serializer;
}
public function persistNew($token_entity) {
if (!is_a($token_entity, static::$entityInterface)) {
throw new \InvalidArgumentException(sprintf('%s does not implement %s.', get_class($token_entity), static::$entityInterface));
}
$values = $this->serializer
->normalize($token_entity);
$values['bundle'] = static::$bundleId;
$new_token = $this->entityTypeManager
->getStorage(static::$entityTypeId)
->create($values);
if ($token_entity instanceof RefreshTokenEntityInterface) {
$access_token = $token_entity
->getAccessToken();
if (!empty($access_token
->getUserIdentifier())) {
$new_token
->set('auth_user_id', $access_token
->getUserIdentifier());
}
}
$new_token
->save();
}
public function revoke($token_id) {
if (!($tokens = $this->entityTypeManager
->getStorage(static::$entityTypeId)
->loadByProperties([
'value' => $token_id,
]))) {
return;
}
$token = reset($tokens);
$token
->revoke();
$token
->save();
}
public function isRevoked($token_id) {
if (!($tokens = $this->entityTypeManager
->getStorage(static::$entityTypeId)
->loadByProperties([
'value' => $token_id,
]))) {
return TRUE;
}
$token = reset($tokens);
return $token
->isRevoked();
}
public function getNew() {
$class = static::$entityClass;
return new $class();
}
}