about summary refs log tree commit diff
path: root/app/validators/blacklisted_email_validator.rb
blob: 16e3abf1298ed080f586e486524a7f89673a68d3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# frozen_string_literal: true

class BlacklistedEmailValidator < ActiveModel::Validator
  def validate(user)
    return if user.valid_invitation?

    @email = user.email

    user.errors.add(:email, I18n.t('users.blocked_email_provider')) if blocked_email?
  end

  private

  def blocked_email?
    on_blacklist? || not_on_whitelist?
  end

  def on_blacklist?
    return true  if EmailDomainBlock.block?(@email)
    return false if Rails.configuration.x.email_domains_blacklist.blank?

    domains = Rails.configuration.x.email_domains_blacklist.gsub('.', '\.')
    regexp  = Regexp.new("@(.+\\.)?(#{domains})", true)

    @email =~ regexp
  end

  def not_on_whitelist?
    return false if Rails.configuration.x.email_domains_whitelist.blank?

    domains = Rails.configuration.x.email_domains_whitelist.gsub('.', '\.')
    regexp  = Regexp.new("@(.+\\.)?(#{domains})$", true)

    @email !~ regexp
  end
end