-
Notifications
You must be signed in to change notification settings - Fork 5
/
ip.rb
43 lines (35 loc) · 945 Bytes
/
ip.rb
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
43
# frozen_string_literal: true
require 'ipaddr'
class MiniDefender::Rules::Ip < MiniDefender::Rule
MODES = %w[any public private]
def initialize(mode = 'any')
raise ArgumentError, 'Invalid mode' unless MODES.include?(mode)
@mode = mode
end
def self.signature
'ip'
end
def self.make(args)
new(args[0] || 'any')
end
def passes?(attribute, value, validator)
ip = IPAddr.new(value.to_s)
(
@mode == 'any' ||
@mode == 'private' && (ip.private? || ip.link_local? || ip.loopback?) ||
@mode == 'public' && !(ip.private? || ip.link_local? || ip.loopback?)
)
rescue IPAddr::InvalidAddressError
false
end
def message(attribute, value, validator)
case @mode
when 'public'
"The value must be a valid public IP address."
when 'private'
"The value must be a valid private IP address."
else
"The value must be a valid IP address."
end
end
end