exchange method

Exchange device code after user verified for token

Implementation

Future<DeviceFlowExchangeResponse> exchange() {
  if (!_response.containsKey("device_code")) {
    throw Exception("Device code not found");
  }

  final headers = <String, String>{
    'Accept': 'application/json',
    'content-type': 'application/json',
  };

  final body = GitHubJson.encode(<String, dynamic>{
    'client_id': clientId,
    'device_code': _response['device_code'],
    'grant_type': grantType,
  });

  return (github == null ? http.Client() : github!.client)
      .post(
        Uri.parse('$baseUrl/login/oauth/access_token'),
        body: body,
        headers: headers,
      )
      .then((response) {
        final json = jsonDecode(response.body) as Map<String, dynamic>;
        if (json['error'] != null) {
          throw Exception(json['error'] ?? "Unknown error");
        }
        return DeviceFlowExchangeResponse(
          json['access_token'],
          json['token_type'],
          (json['scope'] as String).split(','),
          json['interval'] ?? 0,
        );
      });
}