You are here

function oauth2_server_cron in OAuth2 Server 7

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

Implements hook_cron().

File

./oauth2_server.module, line 758
Provides OAuth2 server functionality.

Code

function oauth2_server_cron() {

  // Delete expired tokens and authorization codes.
  $entity_types = [
    'oauth2_server_token',
    'oauth2_server_authorization_code',
  ];
  foreach ($entity_types as $entity_type) {
    $query = new EntityFieldQuery();
    $query
      ->entityCondition('entity_type', $entity_type)
      ->propertyCondition('expires', 0, '<>')
      ->propertyCondition('expires', REQUEST_TIME, '<=');
    $result = $query
      ->execute();
    if (!empty($result[$entity_type])) {
      entity_delete_multiple($entity_type, array_keys($result[$entity_type]));
    }
  }

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

  // No need to do anything if hook_cron() is invoked from simpletest.
  $simpletest = variable_get('simpletest_parent_profile', '');
  if ($needs_keys && !$simpletest) {
    $last_generated = variable_get('oauth2_server_keys_last_generated', 0);

    // Check if the keys were last generated more than 23h30min ago.
    if (REQUEST_TIME - $last_generated > 84600) {
      $keys = oauth2_server_generate_keys();
      variable_set('oauth2_server_keys', $keys);
      variable_set('oauth2_server_keys_last_generated', REQUEST_TIME);
    }
  }
}