You are here

function simple_oauth_cron in Simple OAuth (OAuth2) & OpenID Connect 8

Same name and namespace in other branches
  1. 8.4 simple_oauth.module \simple_oauth_cron()
  2. 8.2 simple_oauth.module \simple_oauth_cron()
  3. 8.3 simple_oauth.module \simple_oauth_cron()
  4. 5.x simple_oauth.module \simple_oauth_cron()

Implements hook_cron().

File

./simple_oauth.module, line 29
Contains simple_oauth.module..

Code

function simple_oauth_cron() {

  /* @var \Drupal\Core\Entity\EntityManagerInterface $manager */
  $manager = \Drupal::service('entity.manager');
  $storage = $manager
    ->getStorage('access_token');
  $query = $storage
    ->getQuery();

  // We only delete access tokens when deleting their expired refresh tokens.
  $ids = $query
    ->condition('expire', REQUEST_TIME, '<')
    ->condition('resource', 'authentication')
    ->execute();
  if (!empty($ids)) {
    $refresh_tokens = $storage
      ->loadMultiple($ids);

    // Get the access tokens associated to this refresh token.
    $access_tokens = array_map(function ($refresh_token) {
      return $refresh_token
        ->get('access_token_id')->entity;
    }, $refresh_tokens);

    // Delete the access tokens.
    $storage
      ->delete(array_filter($access_tokens));

    // Delete the refresh tokens.
    $storage
      ->delete($refresh_tokens);
  }
}