email_mx_validator.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # frozen_string_literal: true
  2. require 'resolv'
  3. class EmailMxValidator < ActiveModel::Validator
  4. def validate(user)
  5. return if user.email.blank?
  6. domain = get_domain(user.email)
  7. if domain.blank?
  8. user.errors.add(:email, :invalid)
  9. elsif !on_allowlist?(domain)
  10. ips, hostnames = resolve_mx(domain)
  11. if ips.empty?
  12. user.errors.add(:email, :unreachable)
  13. elsif on_blacklist?(hostnames + ips)
  14. user.errors.add(:email, :blocked)
  15. end
  16. end
  17. end
  18. private
  19. def get_domain(value)
  20. _, domain = value.split('@', 2)
  21. return nil if domain.nil?
  22. TagManager.instance.normalize_domain(domain)
  23. rescue Addressable::URI::InvalidURIError
  24. nil
  25. end
  26. def on_allowlist?(domain)
  27. return false if Rails.configuration.x.email_domains_whitelist.blank?
  28. Rails.configuration.x.email_domains_whitelist.include?(domain)
  29. end
  30. def resolve_mx(domain)
  31. hostnames = []
  32. ips = []
  33. Resolv::DNS.open do |dns|
  34. dns.timeouts = 5
  35. hostnames = dns.getresources(domain, Resolv::DNS::Resource::IN::MX).to_a.map { |e| e.exchange.to_s }
  36. ([domain] + hostnames).uniq.each do |hostname|
  37. ips.concat(dns.getresources(hostname, Resolv::DNS::Resource::IN::A).to_a.map { |e| e.address.to_s })
  38. ips.concat(dns.getresources(hostname, Resolv::DNS::Resource::IN::AAAA).to_a.map { |e| e.address.to_s })
  39. end
  40. end
  41. [ips, hostnames]
  42. end
  43. def on_blacklist?(values)
  44. EmailDomainBlock.where(domain: values.uniq).any?
  45. end
  46. end