Delete expired tokens

@return string
@throws RuntimeException
332540
public function deleteExpiredTokensAction()
    {
        if (!$this->request instanceof ConsoleRequest) {
            throw new RuntimeException('You can only use this action from console');
        }

        /* @var \ZfrOAuth2\Server\Service\TokenService $accessTokenService */
        $accessTokenService = $this->serviceLocator->get('ZfrOAuth2\Server\Service\AccessTokenService');
        $accessTokenService->deleteExpiredTokens();

        /* @var \ZfrOAuth2\Server\Service\TokenService $refreshTokenService */
        $refreshTokenService = $this->serviceLocator->get('ZfrOAuth2\Server\Service\RefreshTokenService');
        $refreshTokenService->deleteExpiredTokens();

        /* @var \ZfrOAuth2\Server\Service\TokenService $authorizationCodeService */
        $authorizationCodeService = $this->serviceLocator->get('ZfrOAuth2\Server\Service\AuthorizationCodeService');
        $authorizationCodeService->deleteExpiredTokens();

        return "\nExpired tokens were properly deleted!\n\n";
    }
645889
public function isAccessTokenExpired()
  {
    if (!$this->token || !isset($this->token['created'])) {
      return true;
    }

    // If the token is set to expire in the next 30 seconds.
    $expired = ($this->token['created']
        + ($this->token['expires_in'] - 30)) < time();

    return $expired;
  }
1030310
public function validate()
    {
        if (time() > $this->getExpiration()) {
            throw new exceptions\TokenExpiredException('Token is expired.');
        }
        if ($this->getHash() != $this->generateHash()) {
            throw new exceptions\InvalidHashException('Invalid token hash.');
        }
    }
1192359
public function getTokenExpire()
    {
        return $this->_state->token->obtained
            + $this->_state->token->data->expires_in - time();
    }
932057
public function clearExpire()
	{
		$tableName = $this->cache->parseField($this->tableName);
		$expireField = $this->cache->parseField('expire');
		$time = time();
		return $this->cache->execute(<<<SQL
delete from {$tableName} where {$expireField} <> 0 and {$expireField} < {$time}
SQL
);
	}
1035670
private function tokenExpired()
    {
        $tokenExpirationTime = $this->requestTimestamp
            + $this->data[static::RESPONSE_KEY_ACCESS_TOKEN_TTL]
            - static::TTL_CORRECTION_TIME_SEC;

        return $this->tokenExists() && time() > $tokenExpirationTime;
    }
993543
public function cleanupTrash()
    {
        try {
            return $this->innerGateway->cleanupTrash();
        } catch (DBALException $e) {
            throw new RuntimeException('Database error', 0, $e);
        } catch (PDOException $e) {
            throw new RuntimeException('Database error', 0, $e);
        }
    }
613841
public function refreshToken($token = null)
	{
		if (!$this->getOption('userefresh'))
		{
			throw new \RuntimeException('Refresh token is not supported for this OAuth instance.');
		}

		if (!$token)
		{
			$token = $this->getToken();

			if (!array_key_exists('refresh_token', $token))
			{
				throw new \RuntimeException('No refresh token is available.');
			}

			$token = $token['refresh_token'];
		}

		$data['grant_type'] = 'refresh_token';
		$data['refresh_token'] = $token;
		$data['client_id'] = $this->getOption('clientid');
		$data['client_secret'] = $this->getOption('clientsecret');
		$response = $this->http->post($this->getOption('tokenurl'), $data);

		if ($response->code >= 200 || $response->code < 400)
		{
			if ($response->headers['Content-Type'] == 'application/json')
			{
				$token = array_merge(json_decode($response->body, true), array('created' => time()));
			}
			else
			{
				parse_str($response->body, $token);
				$token = array_merge($token, array('created' => time()));
			}

			$this->setToken($token);

			return $token;
		}
		else
		{
			throw new \Exception('Error code ' . $response->code . ' received refreshing token: ' . $response->body . '.');
		}
	}
829161
public function actionClear()
    {
        OAuth2AuthorizationCode::deleteAll(['<', 'expires', time()]);
        OAuth2RefreshToken::deleteAll(['<', 'expires', time()]);
        OAuth2AccessToken::deleteAll(['<', 'expires', time()]);
    }
254107
protected function recycleTokens()
    {
        if (!$this->expire_old) {
            // This is turned off.
            return $this;
        }

        if ($this->useNativeSession) {
            /** @var array<string, array<string, string|int>> $sess */
            $sess =& $_SESSION[$this->sessionIndex];
        } else {
            /** @var array<string, array<string, string|int>> $sess */
            $sess =& $this->session[$this->sessionIndex];
        }
        // Sort by creation time
        \uasort(
            $sess,
            function (array $a, array $b): int {
                return (int) ($a['created'] <=> $b['created']);
            }
        );
        while (\count($sess) > $this->recycle_after) {
            // Let's knock off the oldest one
            \array_shift($sess);
        }
        return $this;
    }
158135
public function getJwtToken()
    {
        if ($this->token && $this->token->isValid()) {
            return $this->token;
        }

        $url = $this->options['token_url'];

        $requestOptions = array_merge(
            $this->getDefaultHeaders(),
            $this->auth->getRequestOptions()
        );

        $response = $this->client->request('POST', $url, $requestOptions);
        $body = json_decode($response->getBody(), true);

        $expiresIn = isset($body[$this->options['expire_key']]) ? $body[$this->options['expire_key']] : null;

        if ($expiresIn) {
            $expiration = new \DateTime('now + ' . $expiresIn . ' seconds');
        } elseif (count($jwtParts = explode('.', $body[$this->options['token_key']])) === 3
            && is_array($payload = json_decode(base64_decode($jwtParts[1]), true))
            // https://tools.ietf.org/html/rfc7519.html#section-4.1.4
            && array_key_exists('exp', $payload)
        ) {
            // Manually process the payload part to avoid having to drag in a new library
            $expiration = new \DateTime('@' . $payload['exp']);
        } else {
            $expiration = null;
        }

        $this->token = new JwtToken($body[$this->options['token_key']], $expiration);

        return $this->token;
    }
1334993
public function getContents()
	{
		// make a copy to leave the original container untouched
		$data = $this->data;

		// delete all expired variables
		foreach($data[static::EXPIRE_DATA_KEY] as $key => $expiration)
		{
			if ($expiration[1] === static::EXPIRE_STATE_EXPIRED)
			{
				unset($data[static::EXPIRE_DATA_KEY][$key]);
				\Arr::delete($data, $this->prefixKey($key));
			}
		}

		// and return what's left over
		return $data;
	}
136838
public function expirationDate()
    {
        $accountExpiry = $this->getAccountExpiry();

        // If the account expiry is zero or the expiry is equal to
        // ActiveDirectory's 'never expire' value,
        // then we'll return null here.
        if ($accountExpiry == 0 || $accountExpiry == $this->getSchema()->neverExpiresDate()) {
            return;
        }

        $unixTime = Utilities::convertWindowsTimeToUnixTime($accountExpiry);

        return (new DateTime())->setTimestamp($unixTime);
    }
15018
protected function autoExpire()
    {
        $lastActivitySecondsAgo = time() - $this->getLastActivityTimestamp();
        $expired = false;
        if ($this->getMaximumAge() !== 0 && $lastActivitySecondsAgo > $this->getMaximumAge()) {
            $this->destroy(sprintf('Session %s was inactive for %s seconds, more than the configured timeout of %s seconds.', $this->getId(), $lastActivitySecondsAgo, $this->getMaximumAge()));
            $expired = true;
        }
        return $expired;
    }
1073943
public function removeExpired() {
		$count = $this->UserTable->removeExpiredRegistrations();
		$this->out(__dn(
			'burzum/user_tools',
			'Removed {0,number,integer} expired registration.',
			'Removed {0,number,integer} expired registrations.',
			$count,
			$count
		));
	}
569966
public function isRememberPasswordTokenExpired()
    {
        if (!$this->rememberPasswordToken() instanceof UserToken) {
            throw new UserTokenNotFoundException();
        }

        return $this->rememberPasswordToken->isExpired(
            $this->rememberPasswordTokenLifetime()
        );
    }
134498
public function removeExpiredRegistrations($conditions = []) {
		$defaults = [
			$this->_table->aliasField($this->_field('emailVerified')) => 0,
			$this->_table->aliasField($this->_field('emailTokenExpires')) . ' <' => date('Y-m-d H:i:s')
		];

		$conditions = Hash::merge($defaults, $conditions);
		$count = $this->_table
			->find()
			->where($conditions)
			->count();

		if ($count > 0) {
			$this->_table->deleteAll($conditions);
		}

		return $count;
	}