Module: Legitbot::Validators::IpRanges::ClassMethods
- Defined in:
- lib/legitbot/validators/ip_ranges.rb
Overview
:nodoc:
Constant Summary collapse
- FAMILIES =
%i[ipv4 ipv6].freeze
- EMPTY_GENERATOR =
proc { [] }
Instance Method Summary collapse
- #check_ranges? ⇒ Boolean
- #ip_ranges(*ips, &block) ⇒ Object
- #load_ips ⇒ Object
- #partition_ips(ips) ⇒ Object
- #reload_ips ⇒ Object
- #valid_ip?(ip) ⇒ Boolean
- #valid_ips ⇒ Object
Instance Method Details
#check_ranges? ⇒ Boolean
33 34 35 |
# File 'lib/legitbot/validators/ip_ranges.rb', line 33 def check_ranges? instance_variable_defined?(:@ip_ranges_loader) end |
#ip_ranges(*ips, &block) ⇒ Object
27 28 29 30 31 |
# File 'lib/legitbot/validators/ip_ranges.rb', line 27 def ip_ranges(*ips, &block) @ip_ranges = partition_ips(ips.flatten) unless ips.empty? @ip_ranges_loader = block_given? ? block : EMPTY_GENERATOR @ip_loader_mutex = Mutex.new end |
#load_ips ⇒ Object
58 59 60 |
# File 'lib/legitbot/validators/ip_ranges.rb', line 58 def load_ips partition_ips(@ip_ranges_loader.call) end |
#partition_ips(ips) ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/legitbot/validators/ip_ranges.rb', line 62 def partition_ips(ips) return [] unless ips&.any? ips .map { |cidr| IPAddr.new(cidr) } .partition(&:ipv4?) .each_with_index .map do |list, index| [FAMILIES[index], build_interval_tree(list)] end.to_h end |
#reload_ips ⇒ Object
52 53 54 55 56 |
# File 'lib/legitbot/validators/ip_ranges.rb', line 52 def reload_ips @ip_loader_mutex.synchronize do @ip_ranges = load_ips end end |
#valid_ip?(ip) ⇒ Boolean
37 38 39 40 41 42 43 44 |
# File 'lib/legitbot/validators/ip_ranges.rb', line 37 def valid_ip?(ip) return true unless check_ranges? return true if valid_ips.empty? obj = IPAddr.new(ip) ranges = valid_ips[obj.ipv4? ? :ipv4 : :ipv6].search(obj.to_i) !ranges.nil? && !ranges.empty? end |
#valid_ips ⇒ Object
46 47 48 49 50 |
# File 'lib/legitbot/validators/ip_ranges.rb', line 46 def valid_ips @ip_loader_mutex.synchronize do @ip_ranges ||= load_ips end end |