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.

25 lines
625 B

  1. # frozen_string_literal: true
  2. require 'resolv'
  3. class EmailMxValidator < ActiveModel::Validator
  4. def validate(user)
  5. return if Rails.env.test? || Rails.env.development?
  6. user.errors.add(:email, I18n.t('users.invalid_email')) if invalid_mx?(user.email)
  7. end
  8. private
  9. def invalid_mx?(value)
  10. _, domain = value.split('@', 2)
  11. return true if domain.nil?
  12. records = Resolv::DNS.new.getresources(domain, Resolv::DNS::Resource::IN::MX).to_a.map { |e| e.exchange.to_s }
  13. records.empty? || on_blacklist?(records)
  14. end
  15. def on_blacklist?(values)
  16. EmailDomainBlock.where(domain: values).any?
  17. end
  18. end