shouldRateLimit method

bool shouldRateLimit({
  1. int maxAttempts = 5,
  2. Duration timeWindow = const Duration(minutes: 15),
})

Checks if authentication should be rate limited.

Returns true if too many failed attempts have occurred within the specified timeWindow, false otherwise.

maxAttempts is the maximum number of allowed attempts. timeWindow is the time window to check within.

Implementation

bool shouldRateLimit({
  int maxAttempts = 5,
  Duration timeWindow = const Duration(minutes: 15),
}) {
  if (_failedAttempts < maxAttempts) {
    return false;
  }

  if (_lastFailedAttempt == null) {
    return false;
  }

  final now = DateTime.now();
  final timeSinceLastAttempt = now.difference(_lastFailedAttempt!);

  // Check if we're still within the time window
  if (timeSinceLastAttempt > timeWindow) {
    // Reset if outside time window
    _failedAttempts = 0;
    _lastFailedAttempt = null;
    return false;
  }

  // Count recent failed attempts within time window
  final cutoffTime = now.subtract(timeWindow);
  final recentAttempts = _failedAttemptHistory
      .where((attempt) => attempt.isAfter(cutoffTime))
      .length;

  return recentAttempts >= maxAttempts;
}