You are here

function oauth2_server_cron in OAuth2 Server 8

Same name and namespace in other branches
  1. 7 oauth2_server.module \oauth2_server_cron()
  2. 2.0.x oauth2_server.module \oauth2_server_cron()

Implements hook_cron().

File

./oauth2_server.module, line 13
The Oauth2 Server module.

Code

function oauth2_server_cron() {
  $request_time = \Drupal::time()
    ->getRequestTime();

  // Delete expired tokens.
  $query = \Drupal::entityQuery('oauth2_server_token');
  $query
    ->condition('expires', 0, '<>');
  $query
    ->condition('expires', $request_time, '<=');
  $result = $query
    ->execute();
  if ($result) {

    /** @var \Drupal\oauth2_server\TokenInterface[] $tokens */
    $tokens = \Drupal::entityTypeManager()
      ->getStorage('oauth2_server_token')
      ->loadMultiple(array_keys($result));
    \Drupal::entityTypeManager()
      ->getStorage('oauth2_server_token')
      ->delete($tokens);
  }

  // Regenerate the keys once a day. Follows Google's practice described in
  // https://developers.google.com/accounts/docs/OAuth2Login#validatinganidtoken
  $needs_keys = Utility::siteNeedsKeys();

  // No need to do anything if hook_cron() is invoked from tests.
  if ($needs_keys) {
    $last_generated = \Drupal::state()
      ->get('oauth2_server.last_generated', 0);

    // Check if the keys were last generated more than 23h30min ago.
    if ($request_time - $last_generated > 84600) {
      $keys = Utility::generateKeys();
      \Drupal::state()
        ->set('oauth2_server.keys', $keys);
      \Drupal::state()
        ->set('oauth2_server.last_generated', $request_time);
    }
  }
}