Sha256: a05847a6d399f39835e290260160e309a6a6a888ff9039b9b8a4e83b5084f4a6

Contents?: true

Size: 1.41 KB

Versions: 2

Compression:

Stored size: 1.41 KB

Contents

require 'ipaddr'
module Hydra
  class IpBasedGroups
    def self.for(remote_ip)
      groups.select { |group| group.include_ip?(remote_ip) }.map(&:name)
    end

    class Group
      attr_accessor :name
      # @param [Hash] h
      def initialize(h)
        @name = h.fetch('name')
        @subnet_strings = h.fetch('subnets')
      end

      def include_ip?(ip_string)
        ip = IPAddr.new(ip_string)
        subnets.any? { |subnet| subnet.include?(ip) }
      end

      private

        def subnets
          @subnets ||= @subnet_strings.map { |s| IPAddr.new(s) }
        end
    end

      def self.groups
        load_groups.fetch('groups').map { |h| Group.new(h) }
      end

      def self.filename
        'config/hydra_ip_range.yml'
      end

      def self.load_groups
        require 'yaml'

        file = File.join(Rails.root, filename)

        unless File.exist?(file)
          raise "ip-range configuration file not found. Expected: #{file}."
        end

        begin
          yml = if Psych::VERSION > '4.0'
            YAML.safe_load(File.read(file), aliases: true)
          else
            YAML.safe_load(File.read(file), [], [], true)
          end
        rescue
          raise("#{filename} was found, but could not be parsed.\n")
        end
        unless yml.is_a? Hash
          raise("#{filename} was found, but was blank or malformed.\n")
        end

        yml.fetch(Rails.env)
      end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hydra-access-controls-13.0.0 lib/hydra/ip_based_groups.rb
hydra-access-controls-12.1.0 lib/hydra/ip_based_groups.rb