exchangeAiinOAuthCode function

Future<AiinOAuthTokens> exchangeAiinOAuthCode({
  1. required String code,
  2. required String state,
  3. Client? client,
  4. String authBaseUrl = aiinAuthBaseUrl,
})

Exchanges the redirect's temporary code + state for AIIN JWTs.

Implementation

Future<AiinOAuthTokens> exchangeAiinOAuthCode({
  required String code,
  required String state,
  http.Client? client,
  String authBaseUrl = aiinAuthBaseUrl,
}) async {
  final response = await _postOrGet(
    method: 'POST',
    url: Uri.parse('$authBaseUrl/api/oauth-proxy/exchange'),
    body: jsonEncode({'code': code, 'state': state}),
    client: client,
  );
  final parsed = _decode(response);
  final access = parsed['access_token'];
  if (access is! String || access.isEmpty) {
    throw AiinAuthException(
      'AIIN token exchange returned no access token',
      code: 'invalid_response',
      statusCode: response.statusCode,
    );
  }
  return AiinOAuthTokens(
    accessToken: access,
    refreshToken: switch (parsed['refresh_token']) {
      String value when value.isNotEmpty => value,
      _ => '',
    },
    tokenType: switch (parsed['token_type']) {
      String value when value.isNotEmpty => value,
      _ => 'Bearer',
    },
    expiresIn: switch (parsed['expires_in']) {
      int value => value,
      _ => 0,
    },
    refreshExpiresIn: switch (parsed['refresh_expires_in']) {
      int value => value,
      _ => 0,
    },
  );
}