user_email_validator.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # frozen_string_literal: true
  2. class UserEmailValidator < ActiveModel::Validator
  3. def validate(user)
  4. return if user.valid_invitation? || user.email.blank?
  5. user.errors.add(:email, :blocked) if blocked_email_provider?(user.email, user.sign_up_ip)
  6. user.errors.add(:email, :taken) if blocked_canonical_email?(user.email)
  7. end
  8. private
  9. def blocked_email_provider?(email, ip)
  10. disallowed_through_email_domain_block?(email, ip) || disallowed_through_configuration?(email) || not_allowed_through_configuration?(email)
  11. end
  12. def blocked_canonical_email?(email)
  13. CanonicalEmailBlock.block?(email)
  14. end
  15. def disallowed_through_email_domain_block?(email, ip)
  16. EmailDomainBlock.block?(email, attempt_ip: ip)
  17. end
  18. def not_allowed_through_configuration?(email)
  19. return false if Rails.configuration.x.email_domains_allowlist.blank?
  20. domains = Rails.configuration.x.email_domains_allowlist.gsub('.', '\.')
  21. regexp = Regexp.new("@(.+\\.)?(#{domains})$", true)
  22. email !~ regexp
  23. end
  24. def disallowed_through_configuration?(email)
  25. return false if Rails.configuration.x.email_domains_denylist.blank?
  26. domains = Rails.configuration.x.email_domains_denylist.gsub('.', '\.')
  27. regexp = Regexp.new("@(.+\\.)?(#{domains})", true)
  28. regexp.match?(email)
  29. end
  30. end