requestAccessCredentials function

Future<AccessCredentials> requestAccessCredentials({
  1. required String clientId,
  2. required Iterable<String> scopes,
  3. String prompt = 'select_account',
  4. @Deprecated('Undocumented feature. Do not include in production code.') String? logLevel,
})

Implementation

Future<AccessCredentials> requestAccessCredentials({
  required String clientId,
  required Iterable<String> scopes,
  String prompt = 'select_account',
  @Deprecated('Undocumented feature. Do not include in production code.')
  String? logLevel,
}) async {
  await gis_loader.loadWebSdk();
  if (logLevel != null) _googleAccountsId.callMethod('setLogLevel', [logLevel]);

  final completer = Completer<AccessCredentials>();

  void callback(gis.TokenResponse response) {
    if (response.error != null) {
      window.console.log(response);
      completer.completeError(
        AuthenticationException(
          response.error!,
          errorDescription: response.error_description,
          errorUri: response.error_uri,
        ),
      );
      return;
    }

    final token = AccessToken(
      response.token_type!,
      response.access_token!,
      expiryDate(response.expires_in!),
    );

    final creds = AccessCredentials(token, null, response.scope);

    completer.complete(creds);
  }

  void errorCallback(gis.GoogleIdentityServicesError? error) {
    if (error != null) {
      completer.completeError(
        AuthenticationException(
          error.type.toString(),
          errorDescription: error.message,
          errorUri:
              'https://developers.google.com/identity/oauth2/web/reference/js-reference#TokenClientConfig',
        ),
      );
    }
  }

  final config = gis.TokenClientConfig(
    callback: allowInterop(callback),
    client_id: clientId,
    scope: scopes.toList(),
    prompt: prompt,
    error_callback: allowInterop(errorCallback),
  );

  final client = gis.oauth2.initTokenClient(config);

  client.requestAccessToken();

  return completer.future;
}