Skip to content

Instantly share code, notes, and snippets.

@j-a4
Last active May 25, 2018 19:23
Show Gist options
  • Save j-a4/702ebf39300b6a9d5a33fe5d4c7b41b0 to your computer and use it in GitHub Desktop.
Save j-a4/702ebf39300b6a9d5a33fe5d4c7b41b0 to your computer and use it in GitHub Desktop.
Email MX validator for Mastodon
# Validates that MX record exists for domain to prevent typos and also block by MX servers
# Use by adding to app/models/user.rb
# validates_with EmailMXValidator, if: :email_changed?
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment