check method
Inspects context and returns a SecurityResult.
Implementations should be side-effect-light with respect to
context.body (avoid destructive mutation) but may freely read/write
context.metadata to communicate with later layers.
Implementation
@override
Future<SecurityResult> check(RequestContext context) async {
final now = context.timestamp;
final userKey =
context.userId != null ? 'ratelimit:user:${context.userId}' : null;
final ipKey = 'ratelimit:ip:${context.ipAddress}';
final userCount = userKey != null ? await _recordAndCount(userKey, now) : 0;
final ipCount = await _recordAndCount(ipKey, now);
final requestCount = userCount > ipCount ? userCount : ipCount;
context.setMeta('requestFrequency', requestCount);
if (requestCount > maxRequests) {
return SecurityResult.block(
message: 'Rate limit exceeded ($requestCount requests within '
'${window.inSeconds}s)',
flags: const ['rate_limit_exceeded'],
riskScore: 0.85,
);
}
return SecurityResult.allow(message: 'Within rate limit');
}