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.

37 lines
957 B

  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. hostnames = []
  12. ips = []
  13. Resolv::DNS.open do |dns|
  14. dns.timeouts = 1
  15. hostnames = dns.getresources(domain, Resolv::DNS::Resource::IN::MX).to_a.map { |e| e.exchange.to_s }
  16. ([domain] + hostnames).uniq.each do |hostname|
  17. ips.concat(dns.getresources(hostname, Resolv::DNS::Resource::IN::A).to_a.map { |e| e.address.to_s })
  18. ips.concat(dns.getresources(hostname, Resolv::DNS::Resource::IN::AAAA).to_a.map { |e| e.address.to_s })
  19. end
  20. end
  21. ips.empty? || on_blacklist?(hostnames + ips)
  22. end
  23. def on_blacklist?(values)
  24. EmailDomainBlock.where(domain: values.uniq).any?
  25. end
  26. end