IpFilter
IpFilter is IP filtering solution for Ruby. Common use case for this is DRM. Uses a GeoIP (or Geo::IP) database to determine the request ip’s location.
Compatibility
-
Supports Ruby version: 1.9.2 to 2.2.0
-
Supports cache store: Memcache, Redis.
-
Supports Rails 3.
Install
As a Gem
Add to your Gemfile:
gem "ip_filter"
and run at the command prompt:
bundle install
Or As a Plugin
At the command prompt:
rails plugin install git://github.com/chtrinh/ip_filter.git
Typical Rails Configuration
# config/initializers/ip_filter.rb
IpFilter.configure do |config|
# Location of GeoIP database files.
config.data_folder = "lib/assets/"
# Level of filtering : Country, city...
config.geoip_level = 'country'
# Type of ip country code to compare by.
config.ip_code_type = "country_code2"
# Accepts a proc that must return an array with corresponding format as :ip_code_type
config.ip_codes = Proc.new { ["FI", "US", "GB"] }
# Accepts a proc that must return an array of IPs or IP range to
config.ip_whitelist = Proc.new { ["22.33.11.0/24", "2.3.1.4"] }
# Exception to throw when IP is NOT allowed.
# Accepts a Proc for fine-grain control of the appropriate response.
config.ip_exception = Proc.new { raise Api::Exception::AuthorizationError.new("You region is blocked!") }
# Cache object (Memcache or Redis).
config.cache = Rails.cache
## MaxMind binary require a configuration file.
# If empty,
# Configuration path for geoipupdate binary
config.geoipupdate_config = '/usr/local/etc/GeoIP.conf'
## S3 credentials ##
# if access_key_id is nil, S3 isn't loaded.
config.access_key_id = nil
# S3 Secret API key
config.secret_access_key = nil
# S3 bucket name
config.bucket_name = 'ottsm-geoip'
end
Default Values
data_folder : “/tmp/geoip”
geo_ip_dat : data/GeoIP.dat
geoip_level : :country
update_method : Proc {}
ip_code_type : nil ip_codes : Proc {}
ip_whitelist : Proc {}
ip_exception : Proc {}
allow_loopback : true
cache : nil
cache_prefix : ‘ip_filter:’
geoipupdate_config : ‘/usr/local/etc/GeoIP.conf’
s3_access_key_id : nil
s3_secret_access_key : nil
s3_bucket_name : ‘ip_filter-geoip’
refresh_delay : 86400
Whitelist Ip
See above configuration.
Validate IP
Add the following method to any controller to validate the Request#ip. IpFilter::Configuration.ip_exception is a Proc which is called when ip is NOT within the specified region/country code and NOT in IP whitelist. You can pass in filter options similar to those in before_filter.
validate_ip
You can also pass a block (with filter options) to be executed when validation of ip fails like so (defaults to IpFilter::Configuration.ip_exception proc if no block present):
validate_ip do
raise Exception.new "Sorry access not granted!"
end
By default, loopback/private network addresses are allowed. You can disable this in like so:
#config/initializers/ip_filter.rb
IpFilter.configure do |config|
config.allow_loopback = false
end
Skip validation of IP
Add the following method to any controller that contains validate_ip to skip over the validation.
skip_validate_ip
Internally it is just skip_before_filter so filter options can be pass to it as well.
skip_validate_ip :only => [:index, :show], :if => lambda { account.roles == "admin" }
Request Geocoding by IP Address
IpFilter adds a location method to the standard Rack::Request object so you can easily look up the location of any HTTP request by IP address. For example, in a Rails controller:
# returns IpFilter::Result object
result = request.location
See “Advanced Geocoding” below for more information about IpFilter::Result objects.
Advanced Geocoding
So far we have looked at shortcuts for assigning geocoding results to object attributes.
Every IpFilter::Result object, result, provides the following data:
-
result.ip- string -
result.country_code- string -
result.country_code2- string -
result.country_code3- string -
result.country_name- string -
result.continent_code- string
Update Geoip database files
To update Geoip database file, you just have to instantiate :
IpFilter::Providers::MaxMind.new
This will update files located in IpFilter::Configuration.data_folder
S3
The database files could also be uploaded or downloaded from S3.
Upload to S3 :
IpFilter.s3.upload!
Download from s3 :
IpFilter.s3.download!
These actions could be done exclusively if you provide you access key ID
and your secret access key in IpFilter configuration.
Caching
It’s easy to cache ip results with IpFilter, just configure a cache store:
IpFilter.configure do |config|
config.cache = Rails.cache
end
Currently only Memcache and redis are supported.
You can also set a custom prefix to be used for cache keys:
IpFilter.configure do |config|
config.cache_prefix = "whatever:"
end
By default the prefix is ip_filter:
Before you implement caching in your app please be sure that doing so does not violate the Terms of Service for your geocoding service.
Use Outside of Rails
You can use IpFilter outside of Rails by calling the IpFilter.search method:
results = IpFilter.search("147.243.3.83")
This returns an array of IpFilter::Result objects. Please see above and in the code for details.
Contributors
Jeremy Le Massu
Based on Chris Trinh gem, helped by Ihor Ratsyborynskyy.
Acknowledgements
The architecture/design of this gem is heavily based off of Geocoder (by Alex Reisner github.com/alexreisner/geocoder). Whereas Geocoder was built with 3rd party API resources in mind, IpFilter uses a local database file (.dat) similar to Geoip (by Clifford Heath github.com/cjheath/geoip).