refresh method

Future<OAuthToken> refresh()

Get a new access token for the current user based on the previously granted refresh token.

Implementation

Future<OAuthToken> refresh() async {
  if (_app == null)
    throw new CarpServiceException(
        message:
            "CARP Service not initialized. Call 'CarpService().configure()' first.");
  if (_currentUser == null)
    throw new CarpServiceException(
        message:
            "No user is authenticated. Call 'CarpService().autheticate()' first.");

  // --data "refresh_token=my-refresh-token&grant_type=refresh_token"
  final loginBody = {
    "refresh_token": "${_currentUser!.token!.refreshToken}",
    "grant_type": "refresh_token"
  };

  final http.Response response = await httpr.post(
    Uri.encodeFull(authEndpointUri),
    headers: _authenticationHeader,
    body: loginBody,
  );

  int httpStatusCode = response.statusCode;
  Map<String, dynamic> responseJson = json.decode(response.body);

  if (httpStatusCode == HttpStatus.ok) {
    OAuthToken refreshedToken = OAuthToken.fromMap(responseJson);
    _currentUser!.authenticated(refreshedToken);
    _authEventController.add(AuthEvent.refreshed);
    return refreshedToken;
  }

  // All other cases are treated as a failed attempt and throws an error
  _authEventController.add(AuthEvent.failed);
  _currentUser = null;
  throw CarpServiceException(
    httpStatus: HTTPStatus(httpStatusCode, response.reasonPhrase),
    message: responseJson["error_description"],
  );
}