email_mx_validator.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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? || domain.include?('..')
  8. user.errors.add(:email, :invalid)
  9. elsif !on_allowlist?(domain)
  10. resolved_ips, resolved_domains = resolve_mx(domain)
  11. if resolved_ips.empty?
  12. user.errors.add(:email, :unreachable)
  13. elsif email_domain_blocked?(resolved_domains, user.sign_up_ip)
  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_allowlist.blank?
  28. Rails.configuration.x.email_domains_allowlist.include?(domain)
  29. end
  30. def resolve_mx(domain)
  31. records = []
  32. ips = []
  33. Resolv::DNS.open do |dns|
  34. dns.timeouts = 5
  35. records = dns.getresources(domain, Resolv::DNS::Resource::IN::MX).to_a.map { |e| e.exchange.to_s }
  36. next if records == [''] # This domain explicitly rejects emails
  37. ([domain] + records).uniq.each do |hostname|
  38. ips.concat(dns.getresources(hostname, Resolv::DNS::Resource::IN::A).to_a.map { |e| e.address.to_s })
  39. ips.concat(dns.getresources(hostname, Resolv::DNS::Resource::IN::AAAA).to_a.map { |e| e.address.to_s })
  40. end
  41. end
  42. [ips, records]
  43. end
  44. def email_domain_blocked?(domains, attempt_ip)
  45. EmailDomainBlock.block?(domains, attempt_ip: attempt_ip)
  46. end
  47. end