issueAuthPasswordResetTokenForUser function

Future<String?> issueAuthPasswordResetTokenForUser({
  1. required AuthStore store,
  2. required String userId,
  3. required Duration ttl,
  4. String generateToken()?,
  5. DateTime? now,
})

Issues a one-time password-reset token for an existing user.

The returned raw token is intended only for delivery through a trusted channel. The configured store receives only its digest. Callers handling a public forgot-password request must return the same response whether this returns a token or null, so account existence is not disclosed.

Implementation

Future<String?> issueAuthPasswordResetTokenForUser({
  required AuthStore store,
  required String userId,
  required Duration ttl,
  String Function()? generateToken,
  DateTime? now,
}) async {
  final normalizedUserId = userId.trim();
  if (normalizedUserId.isEmpty) {
    throw ArgumentError.value(userId, 'userId', 'must be non-empty');
  }
  final user = await Future.sync(() => store.users.findById(normalizedUserId));
  if (user == null) {
    return null;
  }
  final token = generateToken?.call() ?? generateAuthPasswordResetToken();
  final record = buildAuthPasswordResetToken(
    userId: user.id,
    token: token,
    ttl: ttl,
    now: now,
  );
  await Future.sync(() => store.passwordResetTokens.save(record));
  return token;
}