You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.3 KiB

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