|
|
@ -30,32 +30,56 @@ class EmailDomainBlock < ApplicationRecord
|
|
|
|
@history ||= Trends::History.new('email_domain_blocks', id)
|
|
|
|
@history ||= Trends::History.new('email_domain_blocks', id)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
def self.block?(domain_or_domains, attempt_ip: nil)
|
|
|
|
class Matcher
|
|
|
|
domains = Array(domain_or_domains).map do |str|
|
|
|
|
def initialize(domain_or_domains, attempt_ip: nil)
|
|
|
|
domain = begin
|
|
|
|
@uris = extract_uris(domain_or_domains)
|
|
|
|
if str.include?('@')
|
|
|
|
@attempt_ip = attempt_ip
|
|
|
|
str.split('@', 2).last
|
|
|
|
end
|
|
|
|
else
|
|
|
|
|
|
|
|
str
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
TagManager.instance.normalize_domain(domain) if domain.present?
|
|
|
|
def match?
|
|
|
|
rescue Addressable::URI::InvalidURIError
|
|
|
|
blocking? || invalid_uri?
|
|
|
|
nil
|
|
|
|
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
# If some of the inputs passed in are invalid, we definitely want to
|
|
|
|
private
|
|
|
|
# block the attempt, but we also want to register hits against any
|
|
|
|
|
|
|
|
# other valid matches
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
blocked = domains.any?(&:nil?)
|
|
|
|
def invalid_uri?
|
|
|
|
|
|
|
|
@uris.any?(&:nil?)
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
where(domain: domains).find_each do |block|
|
|
|
|
def blocking?
|
|
|
|
blocked = true
|
|
|
|
blocks = EmailDomainBlock.where(domain: domains_with_variants).order(Arel.sql('char_length(domain) desc'))
|
|
|
|
block.history.add(attempt_ip) if attempt_ip.present?
|
|
|
|
blocks.each { |block| block.history.add(@attempt_ip) } if @attempt_ip.present?
|
|
|
|
|
|
|
|
blocks.any?
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
blocked
|
|
|
|
def domains_with_variants
|
|
|
|
|
|
|
|
@uris.flat_map do |uri|
|
|
|
|
|
|
|
|
next if uri.nil?
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
segments = uri.normalized_host.split('.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
segments.map.with_index { |_, i| segments[i..-1].join('.') }
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def extract_uris(domain_or_domains)
|
|
|
|
|
|
|
|
Array(domain_or_domains).map do |str|
|
|
|
|
|
|
|
|
domain = begin
|
|
|
|
|
|
|
|
if str.include?('@')
|
|
|
|
|
|
|
|
str.split('@', 2).last
|
|
|
|
|
|
|
|
else
|
|
|
|
|
|
|
|
str
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Addressable::URI.new.tap { |u| u.host = domain.strip } if domain.present?
|
|
|
|
|
|
|
|
rescue Addressable::URI::InvalidURIError, IDN::Idna::IdnaError
|
|
|
|
|
|
|
|
nil
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def self.block?(domain_or_domains, attempt_ip: nil)
|
|
|
|
|
|
|
|
Matcher.new(domain_or_domains, attempt_ip: attempt_ip).match?
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|