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.

44 lines
1.2 KiB

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