Last active
May 25, 2018 19:23
-
-
Save j-a4/702ebf39300b6a9d5a33fe5d4c7b41b0 to your computer and use it in GitHub Desktop.
Email MX validator for Mastodon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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