Credentials.fromJson constructor
Credentials.fromJson(
- String json
Loads a set of credentials from a JSON-serialized form.
Throws a FormatException if the JSON is incorrectly formatted.
Implementation
factory Credentials.fromJson(String json) {
void validate(condition, message) {
if (condition) return;
throw FormatException('Failed to load credentials: $message.\n\n$json');
}
var parsed;
try {
parsed = jsonDecode(json);
} on FormatException {
validate(false, 'invalid JSON');
}
validate(parsed is Map, 'was not a JSON map');
validate(parsed.containsKey('accessToken'),
'did not contain required field "accessToken"');
validate(
parsed['accessToken'] is String,
'required field "accessToken" was not a string, was '
'${parsed["accessToken"]}');
for (var stringField in ['refreshToken', 'idToken', 'tokenEndpoint']) {
var value = parsed[stringField];
validate(value == null || value is String,
'field "$stringField" was not a string, was "$value"');
}
var scopes = parsed['scopes'];
validate(scopes == null || scopes is List,
'field "scopes" was not a list, was "$scopes"');
var tokenEndpoint = parsed['tokenEndpoint'];
if (tokenEndpoint != null) {
tokenEndpoint = Uri.parse(tokenEndpoint);
}
var expiration = parsed['expiration'];
if (expiration != null) {
validate(expiration is int,
'field "expiration" was not an int, was "$expiration"');
expiration = DateTime.fromMillisecondsSinceEpoch(expiration);
}
return Credentials(parsed['accessToken'],
refreshToken: parsed['refreshToken'],
idToken: parsed['idToken'],
tokenEndpoint: tokenEndpoint,
scopes: (scopes as List).map((scope) => scope as String),
expiration: expiration);
}