File: permissions.rb

package info (click to toggle)
ruby-web-console 4.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 632 kB
  • sloc: ruby: 1,496; javascript: 497; sh: 19; makefile: 4
file content (42 lines) | stat: -rw-r--r-- 976 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
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
40
41
42
# frozen_string_literal: true

require "ipaddr"

module WebConsole
  class Permissions
    # IPv4 and IPv6 localhost should be always allowed.
    ALWAYS_PERMITTED_NETWORKS = %w( 127.0.0.0/8 ::1 )

    def initialize(networks = nil)
      @networks = normalize_networks(networks).map(&method(:coerce_network_to_ipaddr)).uniq
    end

    def include?(network)
      @networks.any? { |permission| permission.include?(network.to_s) }
    rescue IPAddr::InvalidAddressError
      false
    end

    def to_s
      @networks.map(&method(:human_readable_ipaddr)).join(", ")
    end

    private

      def normalize_networks(networks)
        Array(networks).concat(ALWAYS_PERMITTED_NETWORKS)
      end

      def coerce_network_to_ipaddr(network)
        if network.is_a?(IPAddr)
          network
        else
          IPAddr.new(network)
        end
      end

      def human_readable_ipaddr(ipaddr)
        ipaddr.to_range.to_s.split("..").uniq.join("/")
      end
  end
end