email_mx_validator.rb 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # frozen_string_literal: true
  2. require 'resolv'
  3. class EmailMxValidator < ActiveModel::Validator
  4. def validate(user)
  5. user.errors.add(:email, I18n.t('users.invalid_email')) if invalid_mx?(user.email)
  6. end
  7. private
  8. def invalid_mx?(value)
  9. _, domain = value.split('@', 2)
  10. return true if domain.nil?
  11. domain = TagManager.instance.normalize_domain(domain)
  12. hostnames = []
  13. ips = []
  14. Resolv::DNS.open do |dns|
  15. dns.timeouts = 1
  16. hostnames = dns.getresources(domain, Resolv::DNS::Resource::IN::MX).to_a.map { |e| e.exchange.to_s }
  17. ([domain] + hostnames).uniq.each do |hostname|
  18. ips.concat(dns.getresources(hostname, Resolv::DNS::Resource::IN::A).to_a.map { |e| e.address.to_s })
  19. ips.concat(dns.getresources(hostname, Resolv::DNS::Resource::IN::AAAA).to_a.map { |e| e.address.to_s })
  20. end
  21. end
  22. ips.empty? || on_blacklist?(hostnames + ips)
  23. rescue Addressable::URI::InvalidURIError
  24. true
  25. end
  26. def on_blacklist?(values)
  27. EmailDomainBlock.where(domain: values.uniq).any?
  28. end
  29. end