issue method

Future<AuthApiKeyIssued> issue({
  1. required String userId,
  2. required String name,
  3. Iterable<String> scopes = const <String>[],
  4. DateTime? expiresAt,
  5. DateTime? now,
})

Issues a key and returns the raw secret exactly once.

Implementation

Future<AuthApiKeyIssued> issue({
  required String userId,
  required String name,
  Iterable<String> scopes = const <String>[],
  DateTime? expiresAt,
  DateTime? now,
}) async {
  final current = (now ?? _clock()).toUtc();
  final normalizedUserId = _required(userId, 'userId');
  final normalizedName = _normalizeName(name);
  final normalizedScopes = _normalizeScopes(scopes);
  final expiry = _resolveExpiry(expiresAt, current);
  final id = _requiredToken(keyIdGenerator(length: 12), 'key ID');
  final secret = _requiredToken(secretGenerator(length: 32), 'key secret');
  final rawKey = '$keyPrefix.$id.$secret';
  final record = AuthApiKeyRecord(
    id: id,
    userId: normalizedUserId,
    name: normalizedName,
    keyPrefix: '$keyPrefix.${id.substring(0, id.length < 8 ? id.length : 8)}',
    secretHash: hashOpaqueToken(rawKey),
    scopes: normalizedScopes,
    createdAt: current,
    updatedAt: current,
    expiresAt: expiry,
  );
  await store.create(record);
  return AuthApiKeyIssued(
    apiKey: record.toPublic(now: current),
    key: rawKey,
  );
}