Class: CloudflareRails::Importer

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudflare_rails/importer.rb

Defined Under Namespace

Classes: ResponseError

Constant Summary collapse

BASE_URL =
'https://www.cloudflare.com'
IPS_V4_URL =
'/ips-v4/'
IPS_V6_URL =
'/ips-v6/'

Class Method Summary collapse

Class Method Details

.cloudflare_ips(refresh: false) ⇒ Object



60
61
62
63
64
65
66
# File 'lib/cloudflare_rails/importer.rb', line 60

def cloudflare_ips(refresh: false)
  @ips = nil if refresh
  @ips ||= (Importer.fetch_with_cache(:ips_v4) + Importer.fetch_with_cache(:ips_v6)).freeze
rescue StandardError => e
  Rails.logger.error "cloudflare-rails: error fetching ip addresses from Cloudflare (#{e}), falling back to defaults"
  CloudflareRails::FallbackIps::IPS_V4 + CloudflareRails::FallbackIps::IPS_V6
end

.fetch(url) ⇒ Object

Raises:



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/cloudflare_rails/importer.rb', line 37

def fetch(url)
  uri = URI("#{BASE_URL}#{url}")

  resp = Net::HTTP.start(uri.host,
                         uri.port,
                         use_ssl: true,
                         read_timeout: Rails.application.config.cloudflare.timeout) do |http|
    req = Net::HTTP::Get.new(uri)

    http.request(req)
  end

  raise ResponseError, resp unless resp.is_a?(Net::HTTPSuccess)

  resp.body.split("\n").reject(&:blank?).map { |ip| IPAddr.new ip }
end

.fetch_with_cache(type) ⇒ Object



54
55
56
57
58
# File 'lib/cloudflare_rails/importer.rb', line 54

def fetch_with_cache(type)
  Rails.cache.fetch("cloudflare-rails:#{type}", expires_in: Rails.application.config.cloudflare.expires_in) do
    send type
  end
end

.ips_v4Object



33
34
35
# File 'lib/cloudflare_rails/importer.rb', line 33

def ips_v4
  fetch IPS_V4_URL
end

.ips_v6Object



29
30
31
# File 'lib/cloudflare_rails/importer.rb', line 29

def ips_v6
  fetch IPS_V6_URL
end