Class: Cloudflare::Rails::Railtie::Importer

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudflare/rails/railtie.rb

Defined Under Namespace

Classes: ResponseError

Constant Summary collapse

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

Class Method Summary collapse

Class Method Details

.cloudflare_ips(refresh: false) ⇒ Object



83
84
85
86
87
88
89
# File 'lib/cloudflare/rails/railtie.rb', line 83

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(e)
  []
end

.fetch(url) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/cloudflare/rails/railtie.rb', line 58

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

  if resp.is_a?(Net::HTTPSuccess)
    resp.body.split("\n").reject(&:blank?).map { |ip| IPAddr.new ip }
  else
    raise ResponseError, resp
  end
end

.fetch_with_cache(type) ⇒ Object



77
78
79
80
81
# File 'lib/cloudflare/rails/railtie.rb', line 77

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



54
55
56
# File 'lib/cloudflare/rails/railtie.rb', line 54

def ips_v4
  fetch IPS_V4_URL
end

.ips_v6Object



50
51
52
# File 'lib/cloudflare/rails/railtie.rb', line 50

def ips_v6
  fetch IPS_V6_URL
end