exchange function

Future<OAuth2Token> exchange(
  1. OAuth1Token oauth1token,
  2. GarthClient client
)

Implementation

Future<OAuth2Token> exchange(
  OAuth1Token oauth1token,
  GarthClient client,
) async {
  final data = oauth1token.mfaToken != null
      ? {"mfa_token": oauth1token.mfaToken!}
      : <String, String>{};
  final baseUrl = "https://connectapi.${client.domain}/oauth-service/oauth/";
  final url = "${baseUrl}exchange/user/2.0";

  final authHeader = await GarminOAuth1Client.generateHeader(
    "POST",
    url,
    token: oauth1token.oauthToken,
    tokenSecret: oauth1token.oauthTokenSecret,
  );

  final cookieStr =
      client.cookies.entries.map((e) => "${e.key}=${e.value}").join("; ");

  final headers = {
    ...USER_AGENT,
    "Authorization": authHeader,
    "Content-Type": "application/x-www-form-urlencoded",
    if (cookieStr.isNotEmpty) "cookie": cookieStr,
  };

  final response = await http.post(
    Uri.parse(url),
    headers: headers,
    body: data,
  );

  if (response.statusCode != 200) {
    throw GarthException(
      "Failed to exchange OAuth2 token: ${response.statusCode}",
    );
  }

  final tokenJson = jsonDecode(response.body) as Map<String, dynamic>;
  return OAuth2Token.fromJson(setExpirations(tokenJson));
}