DVGoogleServiceAccount.fromJson constructor

DVGoogleServiceAccount.fromJson(
  1. String json
)

Reads the key file. Throws ArgumentError naming what is wrong, never quoting the key.

Implementation

factory DVGoogleServiceAccount.fromJson(String json) {
  final Object? decoded;
  try {
    decoded = jsonDecode(json);
  } on FormatException {
    throw ArgumentError.value(
      '<redacted>',
      'serviceAccount',
      'The FCM service account is not JSON. Paste the key file from the '
          'Firebase console (Project settings, Service accounts) or its '
          'base64.',
    );
  }
  if (decoded is! Map<String, Object?>) {
    throw ArgumentError.value('<redacted>', 'serviceAccount',
        'A service account key file is a JSON object.');
  }
  final Map<String, Object?> file = decoded;
  if (file['type'] != 'service_account') {
    throw ArgumentError.value('<redacted>', 'serviceAccount',
        'Not a service account key file (type is not "service_account"). '
            'FCM HTTP v1 needs a service account, not an API key or a user '
            'credential.');
  }
  String require(String field) {
    final Object? value = file[field];
    if (value is String && value.trim().isNotEmpty) return value;
    throw ArgumentError.value('<redacted>', 'serviceAccount',
        'The service account key file has no "$field".');
  }

  final Uri tokenUri = Uri.parse(
      (file['token_uri'] as String?) ?? 'https://oauth2.googleapis.com/token');
  if (tokenUri.scheme != 'https') {
    throw ArgumentError.value('<redacted>', 'serviceAccount',
        'token_uri must be https: the signed assertion is sent there.');
  }
  return DVGoogleServiceAccount._(
    projectId: require('project_id'),
    clientEmail: require('client_email'),
    tokenUri: tokenUri,
    privateKeyId: file['private_key_id'] as String?,
    privateKeyPem: require('private_key'),
  );
}