Skip to content

Commit

Permalink
added ip_selector
Browse files Browse the repository at this point in the history
  • Loading branch information
rm-Umar committed Sep 19, 2022
1 parent 044d3ed commit 5ba6374
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/ipinfo-rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,25 @@

require 'rack'
require 'ipinfo'
require 'ipinfo-rails/ipselector/default_ipselector'

class IPinfoMiddleware
def initialize(app, cache_options = {})
@app = app
@token = cache_options.fetch(:token, nil)
@ipinfo = IPinfo.create(@token, cache_options)
@filter = cache_options.fetch(:filter, nil)
@ip_selector = cache_options.fetch(:ip_selector, nil)
end

def call(env)
env['called'] = 'yes'
request = Rack::Request.new(env)
ip_selected = if @ip_selector.nil?
DefaultIPSelector.new(request)
else
@ip_selector.new(request)
end

filtered = if @filter.nil?
is_bot(request)
Expand All @@ -24,7 +31,7 @@ def call(env)
if filtered
env['ipinfo'] = nil
else
ip = request.ip
ip = ip_selected.get_ip()
env['ipinfo'] = @ipinfo.details(ip)
end

Expand All @@ -41,4 +48,4 @@ def is_bot(request)
false
end
end
end
end
14 changes: 14 additions & 0 deletions lib/ipinfo-rails/ipselector/default_ipselector.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# frozen_string_literal: true
require 'ipinfo-rails/ipselector/ipselector_interface'

class DefaultIPSelector
include IPSelectorInterface
def initialize(request)
@request = request
end

def get_ip()
return @request.ip
end

end
7 changes: 7 additions & 0 deletions lib/ipinfo-rails/ipselector/ipselector_interface.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# frozen_string_literal: true
module IPSelectorInterface
class InterfaceNotImplemented < StandardError; end
def get_ip()
raise InterfaceNotImplemented
end
end
14 changes: 14 additions & 0 deletions lib/ipinfo-rails/ipselector/xforwarded_ipselector.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# frozen_string_literal: true
require 'ipinfo-rails/ipselector/ipselector_interface'

class XForwardedIPSelector
include IPSelectorInterface
def initialize(request)
@request = request
end

def get_ip()
return @request.env['HTTP_X_FORWARDED_FOR']
end

end

0 comments on commit 5ba6374

Please sign in to comment.