Class: IpChecker

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

Instance Method Summary collapse

Constructor Details

#initialize(project_name) ⇒ IpChecker

Returns a new instance of IpChecker.



4
5
6
# File 'lib/ip_checker.rb', line 4

def initialize(project_name)
  @project_name = project_name
end

Instance Method Details

#is_black_list(connection) ⇒ Object



56
57
58
59
60
61
62
63
64
65
# File 'lib/ip_checker.rb', line 56

def is_black_list(connection)
  auth_type_ip = connection.execute("SELECT *
      FROM
          dtb_ip_address_block
      WHERE
          dtb_ip_address_block.ip_address = 'all'
              AND dtb_ip_address_block.auth_type = 1
              AND dtb_ip_address_block.project = '#{@project_name}';")
  auth_type_ip.first && auth_type_ip.first[2].to_s == '1' ? true : false
end

#is_block_ip(request) ⇒ Object



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
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/ip_checker.rb', line 8

def is_block_ip(request)
  raw_ip = request.env["HTTP_X_FORWARDED_FOR"] || request.remote_ip
  user_ip = raw_ip.to_s.split(',').first&.strip
  connection = ActiveRecord::Base.connection()

  #check blacklist (true) or whitelist (false)
  is_black_list = is_black_list(connection)

  filter_ips = connection.execute("SELECT * FROM dtb_ip_address_block
                                  WHERE dtb_ip_address_block.ip_address != 'all'
                                  AND dtb_ip_address_block.project = '#{@project_name}';")

  if user_ip.nil? || user_ip.empty?
    return is_black_list ? false : true
  end

  ip = parse_ip(user_ip)
  unless ip
    return is_black_list ? false : true
  end

  matched = filter_ips.any? do |row|
    begin
      if row[1].include?"-"
        #match against an explicit IP range
        min, max = row[1].split("-")
        min_ip = parse_ip(min)
        max_ip = parse_ip(max)
        next false unless min_ip && max_ip && min_ip.version == ip.version && max_ip.version == ip.version
        ip.addr >= min_ip.addr && ip.addr <= max_ip.addr
      else
        #match against a CIDR prefix
        net = parse_net(row[1], ip.version)
        next false unless net
        net.contains(ip)
      end
    rescue
      false
    end
  end

  if matched
    return is_black_list ? true : false
  else
    return is_black_list ? false : true
  end
end