class DomainFirewall::IPWhitelist

Public Class Methods

new(app, delegate:, url: nil) click to toggle source
# File lib/domain_firewall/ip_whitelist.rb, line 5
def initialize(app, delegate:, url: nil)
  @app = app
  @delegate = delegate
  @url = url
end

Public Instance Methods

call(env) click to toggle source
# File lib/domain_firewall/ip_whitelist.rb, line 11
def call(env)
  req = Rack::Request.new(env)
  uri = URI(req.url)
  white_list = @delegate.whitelist(uri.host)

  # allow the current request if it is the same as our [url] option.
  return @app.call(env) if @url && @url == req.path

  matches?(req.ip, white_list) ? @app.call(env) : halt_chain_with_response
end

Private Instance Methods

halt_chain_with_response() click to toggle source
# File lib/domain_firewall/ip_whitelist.rb, line 24
def halt_chain_with_response
  response = Rack::Response.new
  if @url
    response.redirect(@url, 303)
  else
    response.status = 403
    response.body = [Rack::Utils::HTTP_STATUS_CODES[403]]
  end
  response.finish
end
matches?(request_ip, white_list) click to toggle source
# File lib/domain_firewall/ip_whitelist.rb, line 35
def matches?(request_ip, white_list)
  return true if white_list === true
  Array(white_list).any? { |ip| request_ip =~ regexp_for_ip(ip) }
end
regexp_for_ip(ip) click to toggle source

@param ip [String] a string representing an ip. Wildcards (*) are acceptable. @return [Regexp]

# File lib/domain_firewall/ip_whitelist.rb, line 43
def regexp_for_ip ip
  Regexp.new("\\A#{ip.gsub(".", '\\.').gsub('*', IP_RANGE)}\\z")
end