mirror of
https://github.com/discourse/discourse.git
synced 2024-11-23 01:16:22 +08:00
3bf3b9a4a5
We validate the *format* of email addresses in many places with a match against a regex, often with very slightly different syntax. Adding a separate EmailAddressValidator simplifies the code in a few spots and feels cleaner. Deprecated the old location in case someone is using it in a plugin. No functionality change is in this commit. Note: the regex used at the moment does not support using address literals, e.g.: * localpart@[192.168.0.1] * localpart@[2001:db8::1]
62 lines
1.8 KiB
Ruby
62 lines
1.8 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
class EmailValidator < ActiveModel::EachValidator
|
|
|
|
def validate_each(record, attribute, value)
|
|
if !EmailAddressValidator.valid_value?(value)
|
|
if Invite === record && attribute == :email
|
|
record.errors.add(:base, I18n.t(:'invite.invalid_email', email: CGI.escapeHTML(value)))
|
|
else
|
|
record.errors.add(attribute, I18n.t(:'user.email.invalid'))
|
|
end
|
|
invalid = true
|
|
end
|
|
|
|
if !EmailValidator.allowed?(value)
|
|
record.errors.add(attribute, I18n.t(:'user.email.not_allowed'))
|
|
invalid = true
|
|
end
|
|
|
|
if !invalid && ScreenedEmail.should_block?(value)
|
|
record.errors.add(attribute, I18n.t(:'user.email.blocked'))
|
|
end
|
|
end
|
|
|
|
def self.allowed?(email)
|
|
if (setting = SiteSetting.allowed_email_domains).present?
|
|
return email_in_restriction_setting?(setting, email) || is_developer?(email)
|
|
elsif (setting = SiteSetting.blocked_email_domains).present?
|
|
return !(email_in_restriction_setting?(setting, email) && !is_developer?(email))
|
|
end
|
|
|
|
true
|
|
end
|
|
|
|
def self.can_auto_approve_user?(email)
|
|
if (setting = SiteSetting.auto_approve_email_domains).present?
|
|
return !!(EmailValidator.allowed?(email) && email_in_restriction_setting?(setting, email))
|
|
end
|
|
|
|
false
|
|
end
|
|
|
|
def self.email_in_restriction_setting?(setting, value)
|
|
domains = setting.gsub('.', '\.')
|
|
regexp = Regexp.new("@(.+\\.)?(#{domains})$", true)
|
|
value =~ regexp
|
|
end
|
|
|
|
def self.is_developer?(value)
|
|
Rails.configuration.respond_to?(:developer_emails) && Rails.configuration.developer_emails.include?(value)
|
|
end
|
|
|
|
def self.email_regex
|
|
Discourse.deprecate(
|
|
"EmailValidator.email_regex is deprecated. Please use EmailAddressValidator instead.",
|
|
output_in_test: true,
|
|
drop_from: '2.9.0',
|
|
)
|
|
EmailAddressValidator.email_regex
|
|
end
|
|
end
|