mirror of
https://github.com/samsonjs/rack-attack.git
synced 2026-04-27 15:07:41 +00:00
Merge pull request #435 from dsantosmerino/refactor/throttle-matched-by
Refactor `Throttle#matched_by?` method
This commit is contained in:
commit
6cfd036c2b
1 changed files with 28 additions and 12 deletions
|
|
@ -23,34 +23,50 @@ module Rack
|
||||||
|
|
||||||
def matched_by?(request)
|
def matched_by?(request)
|
||||||
discriminator = block.call(request)
|
discriminator = block.call(request)
|
||||||
|
|
||||||
return false unless discriminator
|
return false unless discriminator
|
||||||
|
|
||||||
current_period = period.respond_to?(:call) ? period.call(request) : period
|
current_period = period_for(request)
|
||||||
current_limit = limit.respond_to?(:call) ? limit.call(request) : limit
|
current_limit = limit_for(request)
|
||||||
key = "#{name}:#{discriminator}"
|
count = cache.count("#{name}:#{discriminator}", current_period)
|
||||||
count = cache.count(key, current_period)
|
|
||||||
epoch_time = cache.last_epoch_time
|
|
||||||
|
|
||||||
data = {
|
data = {
|
||||||
discriminator: discriminator,
|
discriminator: discriminator,
|
||||||
count: count,
|
count: count,
|
||||||
period: current_period,
|
period: current_period,
|
||||||
limit: current_limit,
|
limit: current_limit,
|
||||||
epoch_time: epoch_time
|
epoch_time: cache.last_epoch_time
|
||||||
}
|
}
|
||||||
|
|
||||||
(request.env['rack.attack.throttle_data'] ||= {})[name] = data
|
|
||||||
|
|
||||||
(count > current_limit).tap do |throttled|
|
(count > current_limit).tap do |throttled|
|
||||||
|
annotate_request_with_throttle_data(request, data)
|
||||||
if throttled
|
if throttled
|
||||||
request.env['rack.attack.matched'] = name
|
annotate_request_with_matched_data(request, data)
|
||||||
request.env['rack.attack.match_discriminator'] = discriminator
|
|
||||||
request.env['rack.attack.match_type'] = type
|
|
||||||
request.env['rack.attack.match_data'] = data
|
|
||||||
Rack::Attack.instrument(request)
|
Rack::Attack.instrument(request)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def period_for(request)
|
||||||
|
period.respond_to?(:call) ? period.call(request) : period
|
||||||
|
end
|
||||||
|
|
||||||
|
def limit_for(request)
|
||||||
|
limit.respond_to?(:call) ? limit.call(request) : limit
|
||||||
|
end
|
||||||
|
|
||||||
|
def annotate_request_with_throttle_data(request, data)
|
||||||
|
(request.env['rack.attack.throttle_data'] ||= {})[name] = data
|
||||||
|
end
|
||||||
|
|
||||||
|
def annotate_request_with_matched_data(request, data)
|
||||||
|
request.env['rack.attack.matched'] = name
|
||||||
|
request.env['rack.attack.match_discriminator'] = data[:discriminator]
|
||||||
|
request.env['rack.attack.match_type'] = type
|
||||||
|
request.env['rack.attack.match_data'] = data
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue