ExpiredCollector.php in Simple OAuth (OAuth2) & OpenID Connect 8.4
File
src/ExpiredCollector.php
View source
<?php
namespace Drupal\simple_oauth;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\Query\QueryException;
use Drupal\Core\Session\AccountInterface;
use Drupal\consumers\Entity\Consumer;
class ExpiredCollector {
protected $tokenStorage;
protected $clientStorage;
protected $dateTime;
public function __construct(EntityTypeManagerInterface $entity_type_manager, TimeInterface $date_time) {
$this->clientStorage = $entity_type_manager
->getStorage('consumer');
$this->tokenStorage = $entity_type_manager
->getStorage('oauth2_token');
$this->dateTime = $date_time;
}
public function collect($limit = 0) {
$query = $this->tokenStorage
->getQuery();
$query
->condition('expire', $this->dateTime
->getRequestTime(), '<');
if (!empty($limit)) {
$query
->range(0, $limit);
}
if (!($results = $query
->execute())) {
return [];
}
return array_values($this->tokenStorage
->loadMultiple(array_values($results)));
}
public function collectForAccount(AccountInterface $account) {
$query = $this->tokenStorage
->getQuery();
$query
->condition('auth_user_id', $account
->id());
$query
->condition('bundle', 'refresh_token', '!=');
$entity_ids = $query
->execute();
$output = $entity_ids ? array_values($this->tokenStorage
->loadMultiple(array_values($entity_ids))) : [];
try {
$clients = array_values($this->clientStorage
->loadByProperties([
'user_id' => $account
->id(),
]));
} catch (QueryException $exception) {
return $output;
}
$tokens = array_reduce($clients, function ($carry, $client) {
return array_merge($carry, $this
->collectForClient($client));
}, $output);
$existing = [];
foreach ($tokens as $token) {
$existing[$token
->id()] = $token;
}
return array_values($existing);
}
public function collectForClient(Consumer $client) {
$query = $this->tokenStorage
->getQuery();
$query
->condition('client', $client
->id());
if (!($entity_ids = $query
->execute())) {
return [];
}
$results = $this->tokenStorage
->loadMultiple(array_values($entity_ids));
return array_values($results);
}
public function deleteMultipleTokens(array $tokens = []) {
$this->tokenStorage
->delete($tokens);
}
}
Classes
Name |
Description |
ExpiredCollector |
Service in charge of deleting or expiring tokens that cannot be used anymore. |