├── .gitignore
├── .rubocop.yml
├── .ruby-version
├── Gemfile
├── README.md
├── ipinfo-rails.gemspec
└── lib
├── ipinfo-rails.rb
└── ipinfo-rails
├── ip_selector
├── default_ip_selector.rb
├── ip_selector_interface.rb
└── xforwarded_ip_selector.rb
└── version.rb
/.gitignore:
--------------------------------------------------------------------------------
1 | /.bundle/
2 | /.yardoc
3 | /Gemfile.lock
4 | /_yardoc/
5 | /coverage/
6 | /doc/
7 | /pkg/
8 | /spec/reports/
9 | /tmp/
10 | ipinfo-rails-*.gem
11 |
--------------------------------------------------------------------------------
/.rubocop.yml:
--------------------------------------------------------------------------------
1 | AllCops:
2 | TargetRubyVersion: 2.5
3 | NewCops: enable
4 |
5 | Layout/IndentationWidth:
6 | Width: 4
7 |
8 | Layout/LineLength:
9 | Enabled: true
10 | Max: 80
11 |
12 | Lint/MissingSuper:
13 | Enabled: false
14 |
15 | Metrics/MethodLength:
16 | Enabled: false
17 |
18 | Metrics/AbcSize:
19 | Enabled: false
20 |
21 | Metrics/ClassLength:
22 | Enabled: false
23 |
24 | Lint/DuplicateMethods:
25 | Enabled: false
26 |
27 | Style/Documentation:
28 | Enabled: false
29 |
30 | Style/ClassAndModuleChildren:
31 | Enabled: false
32 |
33 | Style/MethodCallWithArgsParentheses:
34 | EnforcedStyle: require_parentheses
35 | IgnoreMacros: false
36 | IgnoredPatterns: []
37 | AllowParenthesesInMultilineCall: true
38 | AllowParenthesesInChaining: true
39 | AllowParenthesesInCamelCaseMethod: true
40 |
41 | Style/MethodCallWithoutArgsParentheses:
42 | Enabled: false
43 |
44 | Naming/FileName:
45 | Enabled: false
46 |
47 | Naming/PredicateName:
48 | Enabled: false
49 |
--------------------------------------------------------------------------------
/.ruby-version:
--------------------------------------------------------------------------------
1 | 2.7.2
2 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | source 'https://rubygems.org'
4 |
5 | gemspec
6 |
7 | group :development do
8 | gem 'bundler'
9 | gem 'minitest'
10 | gem 'minitest-reporters'
11 | gem 'rubocop'
12 | end
13 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #
IPinfo Rails Client Library
2 |
3 | This is the official Rails client library for the IPinfo.io IP address API, allowing you to look up your own IP address, or get any of the following details for an IP:
4 |
5 | - [Geolocation](https://ipinfo.io/ip-geolocation-api) (city, region, country, postal code, latitude, and longitude)
6 | - [ASN](https://ipinfo.io/asn-api) (ISP or network operator, associated domain name, and type, such as business, hosting, or company)
7 | - [Company](https://ipinfo.io/ip-company-api) (the name and domain of the business that uses the IP address)
8 | - [Carrier](https://ipinfo.io/ip-carrier-api) (the name of the mobile carrier and MNC and MCC for that carrier if the IP is used exclusively for mobile traffic)
9 |
10 | Check all the data we have for your IP address [here](https://ipinfo.io/what-is-my-ip).
11 |
12 | ## Getting Started
13 |
14 | You'll need an IPinfo API access token, which you can get by signing up for a free account at [https://ipinfo.io/signup](https://ipinfo.io/signup).
15 |
16 | The free plan is limited to 50,000 requests per month, and doesn't include some of the data fields such as IP type and company data. To enable all the data fields and additional request volumes see [https://ipinfo.io/pricing](https://ipinfo.io/pricing)
17 |
18 | ⚠️ Note: This library does not currently support our newest free API https://ipinfo.io/lite. If you’d like to use IPinfo Lite, you can call the [endpoint directly](https://ipinfo.io/developers/lite-api) using your preferred HTTP client. Developers are also welcome to contribute support for Lite by submitting a pull request.
19 |
20 | ### Installation
21 |
22 | 1. Option 1) Add this line to your application's Gemfile:
23 |
24 | ```ruby
25 | gem 'ipinfo-rails'
26 | ```
27 |
28 | Then execute:
29 |
30 | ```bash
31 | $ bundle install
32 | ```
33 |
34 | Option 2) Install it yourself by running the following command:
35 |
36 | ```bash
37 | $ gem install ipinfo-rails
38 | ```
39 |
40 | 1. Open your `config/environment.rb` file or your preferred file in the `config/environment` directory. Add the following code to your chosen configuration file.
41 |
42 | ```ruby
43 | require 'ipinfo-rails'
44 | config.middleware.use(IPinfoMiddleware, {token: ""})
45 | ```
46 |
47 | Note: if editing `config/environment.rb`, this needs to come before `Rails.application.initialize!` and with `Rails.application.` prepended to `config`, otherwise you'll get runtime errors.
48 |
49 | 1. Restart your development server.
50 |
51 | ### Quickstart
52 |
53 | Once configured, `ipinfo-rails` will make IP address data accessible within Rail's `request` object. These values can be accessed at `request.env['ipinfo']`.
54 |
55 | ## Details Data
56 |
57 | `request.env['ipinfo']` is `Response` object that contains all fields listed [IPinfo developer docs](https://ipinfo.io/developers/responses#full-response) with a few minor additions. Properties can be accessed through methods of the same name.
58 |
59 | ```ruby
60 | request.env['ipinfo'].hostname == 'cpe-104-175-221-247.socal.res.rr.com'
61 | ```
62 |
63 | ### Country Name
64 |
65 | `request.env['ipinfo'].country_name` will return the country name, as supplied by the `countries.json` file. See below for instructions on changing that file for use with non-English languages. `request.env['ipinfo'].country` will still return country code.
66 |
67 | ```ruby
68 | request.env['ipinfo'].country == 'US'
69 | request.env['ipinfo'].country_name == 'United States'
70 | ```
71 |
72 | ### IP Address
73 |
74 | `request.env['ipinfo'].ip_address` will return the an `IPAddr` object from the [Ruby Standard Library](https://ruby-doc.org/stdlib-2.5.1/libdoc/ipaddr/rdoc/IPAddr.html). `request.env['ipinfo'].ip` will still return a string.
75 |
76 | ```ruby
77 | request.env['ipinfo'].ip == '104.175.221.247'
78 | request.env['ipinfo'].ip_address ==
79 | ```
80 |
81 | ### Longitude and Latitude
82 |
83 | `request.env['ipinfo'].latitude` and `request.env['ipinfo'].longitude` will return latitude and longitude, respectively, as strings. `request.env['ipinfo'].loc` will still return a composite string of both values.
84 |
85 | ```ruby
86 | request.env['ipinfo'].loc == '34.0293,-118.3570'
87 | request.env['ipinfo'].latitude == '34.0293'
88 | request.env['ipinfo'].longitude == '-118.3570'
89 | ```
90 |
91 | ### Accessing all properties
92 |
93 | `request.env['ipinfo'].all` will return all details data as a hash.
94 |
95 | ```ruby
96 | request.env['ipinfo'].all ==
97 | {
98 | :asn => { :asn => 'AS20001',
99 | :domain => 'twcable.com',
100 | :name => 'Time Warner Cable Internet LLC',
101 | :route => '104.172.0.0/14',
102 | :type => 'isp'},
103 | :city => 'Los Angeles',
104 | :company => { :domain => 'twcable.com',
105 | :name => 'Time Warner Cable Internet LLC',
106 | :type => 'isp'},
107 | :country => 'US',
108 | :country_name => 'United States',
109 | :hostname => 'cpe-104-175-221-247.socal.res.rr.com',
110 | :ip => '104.175.221.247',
111 | :ip_address => ,
112 | :loc => '34.0293,-118.3570',
113 | :latitude => '34.0293',
114 | :longitude => '-118.3570',
115 | :phone => '323',
116 | :postal => '90016',
117 | :region => 'California'
118 | }
119 | ```
120 |
121 | ## Configuration
122 |
123 | In addition to the steps listed in the Installation section, it is possible to configure the library with more detail. The following arguments are allowed and are described in detail below.
124 |
125 | ```ruby
126 | require 'ipinfo-rails/ip_selector/xforwarded_ip_selector'
127 |
128 | config.middleware.use(IPinfoMiddleware, {
129 | token: "",
130 | ttl: "",
131 | maxsize: "",
132 | cache: "",
133 | http_client: "",
134 | countries: "",
135 | filter: "",
136 | ip_selector: XForwardedIPSelector,
137 | })
138 | ```
139 |
140 | ### IP Selection Mechanism
141 |
142 | By default, the source IP on the request is used as the input to IP geolocation.
143 |
144 | Since the actual desired IP may be something else, the IP selection mechanism is configurable.
145 |
146 | Here are some built-in mechanisms:
147 |
148 | - [DefaultIPSelector](./lib/ipinfo-rails/ip_selector/default_ip_selector.rb)
149 | - [XForwardedIPSelector](./lib/ipinfo-rails/ip_selector/xforwarded_ip_selector.rb)
150 |
151 | #### Using a custom IP selector
152 |
153 | In case a custom IP selector is required, you may implement the `IPSelectorInterface` and pass the class to `ip_selector` in config.
154 |
155 | ```ruby
156 | require 'custom-package/custom_ip_selector'
157 |
158 | config.middleware.use(IPinfoMiddleware, {
159 | token: "",
160 | ip_selector: CustomIPSelector,
161 | })
162 | ```
163 |
164 | ### Authentication
165 |
166 | The IPinfo library can be authenticated with your IPinfo API token, which is set in the environment file. It also works without an authentication token, but in a more limited capacity.
167 |
168 | ```ruby
169 | config.middleware.use(IPinfoMiddleware, {token: '123456789abc'})
170 | ```
171 |
172 | ### Caching
173 |
174 | In-memory caching of `details` data is provided by default via the [lrucache](https://www.rubydoc.info/gems/lrucache/0.1.4/LRUCache) gem. This uses an LRU (least recently used) cache with a TTL (time to live) by default. This means that values will be cached for the specified duration; if the cache's max size is reached, cache values will be invalidated as necessary, starting with the oldest cached value.
175 |
176 | #### Modifying cache options
177 |
178 | Cache behavior can be modified by setting the `ttl` and `maxsize` options.
179 |
180 | - Default maximum cache size: 4096 (multiples of 2 are recommended to increase efficiency)
181 | - Default TTL: 24 hours (in seconds)
182 |
183 | ```ruby
184 | config.middleware.use(IPinfoMiddleware, {
185 | ttl: 30,
186 | maxsize: 40
187 | })
188 | ```
189 |
190 | #### Using a different cache
191 |
192 | It's possible to use a custom cache by creating a child class of the [CacheInterface](https://github.com/ipinfo/ruby/blob/master/lib/ipinfo/cache/cache_interface.rb) class and passing this into the handler object with the `cache` keyword argument. FYI this is known as [the Strategy Pattern](https://sourcemaking.com/design_patterns/strategy).
193 |
194 | ```ruby
195 | config.middleware.use(IPinfoMiddleware, {:cache => my_fancy_custom_class})
196 | ```
197 |
198 | If a custom cache is used the `maxsize` and `ttl` settings will not be used.
199 |
200 | ### Using a different HTTP library
201 |
202 | Ruby is notorious for having lots of HTTP libraries. While `Net::HTTP` is a reasonable default, you can set any other that [Faraday supports](https://github.com/lostisland/faraday/tree/29feeb92e3413d38ffc1fd3a3479bb48a0915730#faraday) if you prefer.
203 |
204 | ```ruby
205 | config.middleware.use(IPinfoMiddleware, {:http_client => my_client})
206 | ```
207 |
208 | Don't forget to bundle the custom HTTP library as well.
209 |
210 | ### Internationalization
211 |
212 | When looking up an IP address, the response object includes a `Details.country_name` method which includes the country name based on American English. It is possible to return the country name in other languages by setting the countries setting when creating the IPinfo object.
213 |
214 | The file must be a `.json` file with the following structure:
215 |
216 | ```ruby
217 | {
218 | "BD": "Bangladesh",
219 | "BE": "Belgium",
220 | "BF": "Burkina Faso",
221 | "BG": "Bulgaria"
222 | ...
223 | }
224 | ```
225 |
226 | ```ruby
227 | config.middleware.use(IPinfoMiddleware, {:countries => })
228 | ```
229 |
230 | ### Filtering
231 |
232 | By default, `ipinfo-rails` filters out requests that have `bot` or `spider` in the user-agent. Instead of looking up IP address data for these requests, the `request.env['ipinfo']` attribute is set to `nil`. This is to prevent you from unnecessarily using up requests on non-user traffic.
233 |
234 | To set your own filtering rules, *thereby replacing the default filter*, you can set `:filter` to your own, custom callable function which satisfies the following rules:
235 |
236 | - Accepts one request.
237 | - Returns *True to filter out, False to allow lookup*
238 |
239 | To use your own filter rules:
240 |
241 | ```ruby
242 | config.middleware.use(IPinfoMiddleware, {
243 | filter: ->(request) {request.ip == '127.0.0.1'}
244 | })
245 | ```
246 |
247 | This simple lambda function will filter out requests coming from your local computer.
248 |
249 | ## Other Libraries
250 |
251 | There are official IPinfo client libraries available for many languages including PHP, Go, Java, Ruby, and many popular frameworks such as Django, Rails, and Laravel. There are also many third-party libraries and integrations available for our API.
252 |
253 | ## About IPinfo
254 |
255 | Founded in 2013, IPinfo prides itself on being the most reliable, accurate, and in-depth source of IP address data available anywhere. We process terabytes of data to produce our custom IP geolocation, company, carrier, privacy detection (VPN, proxy, Tor), hosted domains, and IP type data sets. Our API handles over 40 billion requests a month for 100,000 businesses and developers.
256 |
257 | 
258 |
--------------------------------------------------------------------------------
/ipinfo-rails.gemspec:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | lib = File.expand_path('lib', __dir__)
4 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5 |
6 | require 'ipinfo-rails/version'
7 |
8 | Gem::Specification.new do |s|
9 | s.name = 'ipinfo-rails'
10 | s.version = IPinfoRails::VERSION
11 | s.required_ruby_version = '>= 2.5.0'
12 | s.date = '2018-12-10'
13 | s.summary = 'The official Rails gem for IPinfo. IPinfo prides itself on ' \
14 | 'being the most reliable, accurate, and in-depth source of ' \
15 | 'IP address data available anywhere. We process terabytes ' \
16 | 'of data to produce our custom IP geolocation, company, ' \
17 | 'carrier and IP type data sets. You can visit our developer ' \
18 | 'docs at https://ipinfo.io/developers.'
19 | s.description = s.summary
20 | s.authors = ['IPinfo releases']
21 | s.email = ['releases@ipinfo.io']
22 | s.homepage = 'https://ipinfo.io'
23 | s.license = 'Apache-2.0'
24 |
25 | s.add_runtime_dependency 'IPinfo', '~> 1.0.1'
26 | s.add_runtime_dependency 'rack', '~> 2.0'
27 |
28 | s.files = `git ls-files -z`.split("\x0").reject do |f|
29 | f.match(%r{^(test|spec|features)/})
30 | end
31 | s.require_paths = ['lib']
32 | end
33 |
--------------------------------------------------------------------------------
/lib/ipinfo-rails.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | require 'rack'
4 | require 'ipinfo'
5 | require 'ipinfo-rails/ip_selector/default_ip_selector'
6 |
7 | class IPinfoMiddleware
8 | def initialize(app, options = {})
9 | @app = app
10 | @token = options.fetch(:token, nil)
11 | @ipinfo = IPinfo.create(@token, options)
12 | @filter = options.fetch(:filter, nil)
13 | @ip_selector = options.fetch(:ip_selector, DefaultIPSelector)
14 | end
15 |
16 | def call(env)
17 | env['called'] = 'yes'
18 | request = Rack::Request.new(env)
19 | ip_selector = @ip_selector.new(request)
20 | filtered = if @filter.nil?
21 | is_bot(request)
22 | else
23 | @filter.call(request)
24 | end
25 |
26 | if filtered
27 | env['ipinfo'] = nil
28 | else
29 | ip = ip_selector.get_ip()
30 | env['ipinfo'] = @ipinfo.details(ip)
31 | end
32 |
33 | @app.call(env)
34 | end
35 |
36 | private
37 |
38 | def is_bot(request)
39 | if request.user_agent
40 | user_agent = request.user_agent.downcase
41 | user_agent.include?('bot') || user_agent.include?('spider')
42 | else
43 | false
44 | end
45 | end
46 | end
47 |
--------------------------------------------------------------------------------
/lib/ipinfo-rails/ip_selector/default_ip_selector.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 | require 'ipinfo-rails/ip_selector/ip_selector_interface'
3 |
4 | class DefaultIPSelector
5 | include IPSelectorInterface
6 |
7 | def initialize(request)
8 | @request = request
9 | end
10 |
11 | def get_ip()
12 | return @request.ip
13 | end
14 | end
15 |
--------------------------------------------------------------------------------
/lib/ipinfo-rails/ip_selector/ip_selector_interface.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | module IPSelectorInterface
4 | class InterfaceNotImplemented < StandardError; end
5 | def get_ip()
6 | raise InterfaceNotImplemented
7 | end
8 | end
9 |
--------------------------------------------------------------------------------
/lib/ipinfo-rails/ip_selector/xforwarded_ip_selector.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 | require 'ipinfo-rails/ip_selector/ip_selector_interface'
3 |
4 | class XForwardedIPSelector
5 | include IPSelectorInterface
6 |
7 | def initialize(request)
8 | @request = request
9 | end
10 |
11 | def get_ip()
12 | x_forwarded = @request.env['HTTP_X_FORWARDED_FOR']
13 | if !x_forwarded || x_forwarded.empty?
14 | return @request.ip
15 | else
16 | return x_forwarded.split(',' , -1)[0]
17 | end
18 | end
19 | end
20 |
--------------------------------------------------------------------------------
/lib/ipinfo-rails/version.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | module IPinfoRails
4 | VERSION = '1.0.1'
5 | end
6 |
--------------------------------------------------------------------------------