You are here

public function AccessToken::refresh in Simple OAuth (OAuth2) & OpenID Connect 8

If this is an refresh token, the refresh token will refresh and provide a new access token

Return value

\Drupal\simple_oauth\AccessTokenInterface

Overrides AccessTokenInterface::refresh

File

src/Entity/AccessToken.php, line 384

Class

AccessToken
Defines the Access Token entity.

Namespace

Drupal\simple_oauth\Entity

Code

public function refresh() {
  if (!$this
    ->isRefreshToken()) {
    return NULL;
  }

  // Find / generate the access token for this refresh token.

  /* @var \Drupal\simple_oauth\AccessTokenInterface $current_access_token */
  $current_access_token = $this
    ->get('access_token_id')->entity;
  if ($current_access_token && $current_access_token
    ->get('expire')->value > REQUEST_TIME) {
    return $current_access_token;
  }

  // If there is no valid token to be found, refresh it by generating a new
  // one.
  $values = [
    'expire' => static::defaultExpiration(),
    'user_id' => $this
      ->get('user_id')->target_id,
    'auth_user_id' => $this
      ->get('auth_user_id')->target_id,
    'resource' => $current_access_token ? $current_access_token
      ->get('resource')->target_id : 'global',
    'created' => REQUEST_TIME,
    'changed' => REQUEST_TIME,
  ];

  /* @var AccessTokenInterface $access_token */
  $store = \Drupal::entityManager()
    ->getStorage('access_token');
  $access_token = $store
    ->create($values);

  // The old refresh / access tokens is no longer needed.
  $this
    ->delete();
  if ($current_access_token) {

    // Since we are removing the refresh token we also delete the access.
    $current_access_token
      ->delete();
  }

  // Saving the access token will generate a refresh token for that one too.
  $access_token
    ->save();
  return $access_token;
}