Skip to content
Permalink
Browse files

Add EmailMXValidator

  • Loading branch information...
bsky
bsky committed May 22, 2018
1 parent 4c9d5a5 commit c8054875d485152cc71f2bac84b4b9d339f46f3b
Showing with 17 additions and 0 deletions.
  1. +1 −0 app/models/user.rb
  2. +16 −0 app/validators/email_mx_validator.rb
@@ -65,6 +65,7 @@ class User < ApplicationRecord

validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
validates_with BlacklistedEmailValidator, if: :email_changed?
validates_with EmailMXValidator, if: :email_changed?

scope :recent, -> { order(id: :desc) }
scope :admins, -> { where(admin: true) }
@@ -0,0 +1,16 @@
# frozen_string_literal: true
require 'resolv'
class EmailMXValidator < ActiveModel::Validator
def validate(user)
domain = user.email.split('@', 2).last
mxs = Resolv::DNS.new.getresources(domain, Resolv::DNS::Resource::IN::MX).to_a.map { |e| e.exchange.to_s }

user.errors.add(:email, "Email address does not appear to be valid. Please check that you've typed it correctly.") if mxs.empty? || blocked_mx?(mxs)
end

private

def blocked_mx?(mxs)
EmailDomainBlock.where('domain IN (?)', mxs).exists?
end
end

0 comments on commit c805487

Please sign in to comment.
You can’t perform that action at this time.