2019-08-08 21:04:19 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class DomainValidator < ActiveModel::EachValidator
|
2024-09-10 12:00:40 +00:00
|
|
|
MAX_DOMAIN_LENGTH = 256
|
|
|
|
MIN_LABEL_LENGTH = 1
|
|
|
|
MAX_LABEL_LENGTH = 63
|
2024-12-09 14:52:49 +00:00
|
|
|
ALLOWED_CHARACTERS_RE = /^[a-z0-9-]+$/i
|
2024-09-10 12:00:40 +00:00
|
|
|
|
2019-08-08 21:04:19 +00:00
|
|
|
def validate_each(record, attribute, value)
|
|
|
|
return if value.blank?
|
|
|
|
|
2024-09-10 12:00:40 +00:00
|
|
|
(options[:multiline] ? value.split : [value]).each do |domain|
|
|
|
|
_, domain = domain.split('@') if options[:acct]
|
|
|
|
|
|
|
|
next if domain.blank?
|
2019-08-30 00:19:17 +00:00
|
|
|
|
2024-09-10 12:00:40 +00:00
|
|
|
record.errors.add(attribute, options[:multiline] ? :invalid_domain_on_line : :invalid, value: domain) unless compliant?(domain)
|
|
|
|
end
|
2019-08-08 21:04:19 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def compliant?(value)
|
2024-09-10 12:00:40 +00:00
|
|
|
uri = Addressable::URI.new
|
|
|
|
uri.host = value
|
|
|
|
uri.normalized_host.size < MAX_DOMAIN_LENGTH && uri.normalized_host.split('.').all? { |label| label.size.between?(MIN_LABEL_LENGTH, MAX_LABEL_LENGTH) && label =~ ALLOWED_CHARACTERS_RE }
|
2019-08-30 00:19:17 +00:00
|
|
|
rescue Addressable::URI::InvalidURIError, IDN::Idna::IdnaError
|
2019-08-08 21:04:19 +00:00
|
|
|
false
|
|
|
|
end
|
|
|
|
end
|