Class: Rack::TorBlock

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/tor_block.rb

Constant Summary collapse

DEFAULT_REDIRECT =

We’re sorry from Google

'https://sorry.google.com'.freeze
GO_AWAY =
[302, { 'Content-Type' => 'text', 'Location' => DEFAULT_REDIRECT }, []].freeze
REMOTE_IP_KEY =
'action_dispatch.remote_ip'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ TorBlock

Returns a new instance of TorBlock.



10
11
12
# File 'lib/rack/tor_block.rb', line 10

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/rack/tor_block.rb', line 14

def call(env)
  remote_ip = env[REMOTE_IP_KEY] || Rack::Request.new(env).ip
  if tor?(remote_ip)
    GO_AWAY
  else
    @app.call(env)
  end
end

#tor?(remote_ip) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
# File 'lib/rack/tor_block.rb', line 24

def tor?(remote_ip)
  key = "tor/#{remote_ip}"
  Rails.cache.fetch(key, expires_in: 6.hours) do
    Rack::IP.new(remote_ip).tor?
  end
rescue # In case of cache failure
  false
end