authenticateWithRefreshToken method

Future<CarpUser> authenticateWithRefreshToken(
  1. String refreshToken
)

Authenticate using the refreshToken previously obtained from this CARP service.

Return the signed in user (with an OAuthToken access token), if successful. Throws a CarpServiceException if not successful.

Implementation

Future<CarpUser> authenticateWithRefreshToken(String refreshToken) async {
  final loginBody = {
    "refresh_token": refreshToken,
    "grant_type": "refresh_token",
  };

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

  int httpStatusCode = response.statusCode;
  String responseBody = response.body;
  if (responseBody.isEmpty) responseBody = '{}';
  Map<String, dynamic> responseJson =
      json.decode(responseBody) as Map<String, dynamic>;

  if (httpStatusCode == HttpStatus.ok) {
    OAuthToken refreshedToken = OAuthToken.fromMap(responseJson);

    _currentUser = CarpUser()..authenticated(refreshedToken);
    await getCurrentUserProfile();

    _authEventController.add(AuthEvent.authenticated);
    return _currentUser!;
  }

  // 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"].toString(),
  );
}