Class: AuthorizedNetworks::Instance

Inherits:
Object
  • Object
show all
Defined in:
lib/authorized_networks/instance.rb

Instance Method Summary collapse

Constructor Details

#initialize(config = nil, &block) ⇒ Instance

Returns a new instance of Instance.



6
7
8
9
# File 'lib/authorized_networks/instance.rb', line 6

def initialize(config = nil, &block)
  @config = config || Config.new
  block.call(@config) if block_given?
end

Instance Method Details

#networksHash<Symbol,Array>

Return a hash of all configured network groups

Returns:

  • (Hash<Symbol,Array>)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/authorized_networks/instance.rb', line 14

def networks
  if @networks && @networks_cached_at && (@networks_cached_at + @config.network_list_cache_ttl) >= Time.now.utc
    # If we have cached some networks and it has expired, clear the
    # cache so we can get a new copy of the networks list.
    @networks = nil
  end

  @networks ||= begin
    if @config.networks
      if @config.networks.is_a?(Proc)
        normalize_ips(@config.networks.call)
      elsif @config.networks.is_a?(Hash)
        normalize_ips(@config.networks)
      elsif @config.networks.is_a?(Array)
        normalize_ips(:default => @config.networks)
      else
        {}
      end
    elsif File.exist?(@config.networks_file_path)
      @networks_cached_at = Time.now.utc
      normalize_ips(YAML.safe_load(File.read(@config.networks_file_path)))
    else
      raise NetworksConfigFileNotFoundError, "No config file was found at #{@config.networks_file_path}"
    end
  end
end

#valid_ip!(ip, options = {}) ⇒ True

Is the given IP a valid IP? Raises an error if not

Returns:

  • (True)


64
65
66
# File 'lib/authorized_networks/instance.rb', line 64

def valid_ip!(ip, options = {})
  valid_ip?(ip, options) || raise(AuthorizedNetworks::UnauthorizedNetworkError, "#{ip} is not a valid IP")
end

#valid_ip?(ip, options = {}) ⇒ Boolean

Is the given IP a valid IP?

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/authorized_networks/instance.rb', line 44

def valid_ip?(ip, options = {})
  return true if @config.disabled?

  ip = IPAddr.new(ip.to_s) rescue nil
  return false unless ip.is_a?(IPAddr)
  groups = options[:groups] || @config.default_groups
  groups.each do |group|
    if group_ips = networks[group.to_sym]
      if group_ips.any? { |gip| gip.include?(ip) }
        return true
      end
    end
  end
  return false
end