getAuthorizationCode static method

Future<AuthorizationCodeV2> getAuthorizationCode({
  1. required String clientId,
  2. required String redirectURI,
  3. List<String> scopes = const ["users.read", "tweet.read", "follows.read"],
})

Implementation

static Future<AuthorizationCodeV2> getAuthorizationCode({
  required String clientId,
  required String redirectURI,
  List<String> scopes = const ["users.read","tweet.read","follows.read"]
}) async {
  final state = createCryptoRandomString();
  final codeVerifier = createCryptoRandomString();
  final resultURI = await _doRequest(
    clientId: clientId,
    redirectURI: redirectURI,
    state: state,
    codeVerifier: codeVerifier,
    scopes: scopes
  );

  if (resultURI?.isEmpty ?? true) {
    throw CanceledByUserException();
  }

  final queries = Uri.splitQueryString(Uri.parse(resultURI!).query);
  if (queries['error'] != null) {
    throw Exception('Error Response: ${queries['error']}');
  }

  // The user cancelled the login flow.
  if (queries['denied'] != null) {
    throw CanceledByUserException();
  }

  final authorizationCode = queries['code'];
  final resultState = queries['state'];
  if (resultState != state) {
    throw Exception('Error: Invalid state');
  }
  if (authorizationCode == null) {
    throw Exception('Error: No authorization code found');
  }
  return AuthorizationCodeV2(
    code: authorizationCode,
    codeVerifier: codeVerifier,
  );
}