Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get max_requests and period from lambda #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/rack/defense.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,15 @@ def initialize

def throttle(rule_name, max_requests, period, &block)
raise ArgumentError, 'rule name should not be nil' unless rule_name
counter = ThrottleCounter.new(rule_name, max_requests, period, store)
throttles[rule_name] = lambda do |req|

throttles[rule_name] = lambda do |req|
max_requests = max_requests.respond_to?(:call) ? max_requests.call(req) : max_requests
period = period.respond_to?(:call) ? period.call(req) : period

raise ArgumentError, 'max_requests should be a number' unless max_requests.is_a?(Numeric)
raise ArgumentError, 'period should be a number' unless period.is_a?(Numeric)

counter = ThrottleCounter.new(rule_name, max_requests, period, store)
key = block.call(req)
key if key && counter.throttle?(key)
end
Expand Down
2 changes: 1 addition & 1 deletion lib/rack/defense/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module Rack
class Defense
VERSION = '0.2.5'
VERSION = '0.3.1'
end
end
14 changes: 14 additions & 0 deletions spec/defense_throttle_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ def window

before do
@start_time = Time.utc(2015, 10, 30, 21, 0, 0)
@user = {
:name => "tester man",
:max_requests => 5,
:period => window
}

#
# configure the Rack::Defense middleware with throttling
Expand All @@ -27,6 +32,15 @@ def window
config.throttle('api', 5, window) do |req|
req.env['HTTP_AUTHORIZATION'] if %r{^/api/} =~ req.path
end

# get max_requests and period from a object in lambda
max_requests = lambda{ |req| @user[:max_requests] }
period = lambda{ |req| @user[:period] }

config.throttle('api', max_requests, period) do |req|
req.env['HTTP_AUTHORIZATION'] if %r{^/api/} =~ req.path
end

end
end
it 'allow ok post' do
Expand Down