refreshToken method

Future<AccessTokenResponse> refreshToken(
  1. AccessTokenResponse curTknResp
)

Performs a refresh_token request using the refreshToken.

Implementation

Future<AccessTokenResponse> refreshToken(
    AccessTokenResponse curTknResp) async {
  var tknResp;
  var refreshToken = curTknResp.refreshToken!;
  try {
    tknResp = await client.refreshToken(refreshToken,
        clientId: clientId,
        clientSecret: clientSecret,
        scopes: curTknResp.scope);
  } catch (_) {
    return await fetchToken();
  }

  if (tknResp == null) {
    throw OAuth2Exception('Unexpected error');
  } else if (tknResp.isValid()) {
    //If the response doesn't contain a refresh token, keep using the current one
    if (!tknResp.hasRefreshToken()) {
      tknResp.refreshToken = refreshToken;
    }

    await tokenStorage.addToken(tknResp);
  } else {
    if (tknResp.error == 'invalid_grant') {
      //The refresh token is expired too
      await tokenStorage.deleteToken(scopes ?? []);
      //Fetch another access token
      tknResp = await getToken();
    } else {
      throw OAuth2Exception(tknResp.error,
          errorDescription: tknResp.errorDescription);
    }
  }

  return tknResp;
}