authenticate method
Resolves authorization to a principal on tenant, or the current
tenant when none is given.
Implementation
Future<DVApiAuthentication> authenticate(
String? authorization, {
String? tenant,
}) async {
final String? credential = credentialOf(authorization);
if (credential == null) return DVApiAuthentication.none;
final String requested = tenant ?? const DVTenants().currentTenant;
try {
final _DVPlatformRuntime? runtime = await _ready();
if (runtime == null) {
return const DVApiAuthentication.refused(503, 'Service Unavailable');
}
final DVApiPrincipal? principal =
credential.startsWith(DVApiKeys.keyPrefix)
? await runtime.keys.authenticate(credential, tenant: requested)
: await runtime.oauth?.authenticate(credential, tenant: requested);
if (principal == null) {
return const DVApiAuthentication.refused(
401,
'Unauthorized',
challenge: _challenge,
);
}
final MiddlewareContext context = MiddlewareContext()
..data[DVApiKeys.principalKey] = principal;
await runtime.rateLimit(null, context);
if (!context.shouldContinue) {
return context.data['diagnostic'] == 'DV-APIKEY-006'
? const DVApiAuthentication.refused(429, 'Too Many Requests')
// A plan the key names and the declaration does not: refused
// rather than let through unmetered.
: const DVApiAuthentication.refused(403, 'Forbidden');
}
return DVApiAuthentication.authenticated(principal);
} on Object catch (error) {
// The type only. An adapter's message can quote what it was given.
DVObservability.logger.error(
'Platform API authentication failed (${error.runtimeType}); the '
'request was refused.',
);
return const DVApiAuthentication.refused(503, 'Service Unavailable');
}
}