class Rack::Defense

Constants

VERSION

Attributes

config[RW]

Public Class Methods

ban?(req) { |ban_callbacks, req, matching_rule| ... } click to toggle source
# File lib/rack/defense.rb, line 73
def ban?(req)
  entry = config.bans.find { |_, filter| filter.call(req) }
  matching_rule = entry[0] if entry
  yield config.ban_callbacks, req, matching_rule if matching_rule && block_given?
  matching_rule
end
new(app) click to toggle source
# File lib/rack/defense.rb, line 90
def initialize(app)
  @app = app
end
setup() { |config| ... } click to toggle source
# File lib/rack/defense.rb, line 68
def setup
  self.config = Config.new
  yield config
end
throttle?(req) { |throttle_callbacks, req, matching_rules| ... } click to toggle source
# File lib/rack/defense.rb, line 80
def throttle?(req)
  matching_rules = config.throttles.
      map { |rule_name, filter| [rule_name, filter.call(req)] }.
      select { |e| e[1] }.
      to_h
  yield config.throttle_callbacks, req, matching_rules if matching_rules.any? && block_given?
  matching_rules if matching_rules.any?
end

Public Instance Methods

call(env) click to toggle source
# File lib/rack/defense.rb, line 94
def call(env)
  klass, config = self.class, self.class.config
  req = ::Rack::Request.new(env)

  if klass.ban?(req, &method(:invoke_callbacks))
    config.banned_response.call(env)
  elsif klass.throttle?(req, &method(:invoke_callbacks))
    config.throttled_response.call(env)
  else
    @app.call(env)
  end
end

Private Instance Methods

invoke_callbacks(callbacks, req, rule_data) click to toggle source
# File lib/rack/defense.rb, line 109
def invoke_callbacks(callbacks, req, rule_data)
  callbacks.each do |callback|
    begin
      callback.call(req, rule_data)
    rescue
      # mute exception
    end
  end
end