feat(User.validation): validates email when env var is present

This commit is contained in:
Martin 2024-02-12 12:39:43 +01:00 committed by mfo
parent 25f92a7760
commit 05193e1d1e
5 changed files with 115 additions and 6 deletions

View file

@ -33,10 +33,15 @@ class User < ApplicationRecord
accepts_nested_attributes_for :france_connect_information
default_scope { eager_load(:instructeur, :administrateur, :expert) }
before_validation -> { sanitize_email(:email) }
before_validation -> { sanitize_email(:email) }
validate :does_not_merge_on_self, if: :requested_merge_into_id_changed?
with_options if: :elligible_to_new_validation? do
before_validation :remove_devise_email_validator
validates :email, strict_email: true
end
def validate_password_complexity?
administrateur?
end
@ -268,4 +273,18 @@ class User < ApplicationRecord
def link_invites!
Invite.where(email: email).update_all(user_id: id)
end
def elligible_to_new_validation?
StrictEmailValidator.elligible_to_new_validation?(self)
end
def remove_devise_email_validator
_validators[:email]&.reject! { _1.is_a?(ActiveModel::Validations::FormatValidator) }
_validate_callbacks.each do |callback|
next if !callback.filter.is_a?(ActiveModel::Validations::FormatValidator)
next if !callback.filter.attributes.include? :email
callback.filter.attributes.delete(:email)
end
end
end

View file

@ -6,14 +6,22 @@ class StrictEmailValidator < ActiveModel::EachValidator
REGEXP = /\A[^@\s]+@[^@\s\.]+\.[^@\s]{2,}\z/
def validate_each(record, attribute, value)
if value.present? && !REGEXP.match?(value)
record.errors.add(attribute, :format)
if value.present? && !regexp_for(record).match?(value)
record.errors.add(attribute, :invalid_email_format)
end
end
def regexp_for(record)
if StrictEmailValidator.elligible_to_new_validation?(record)
REGEXP
else
Devise.email_regexp
end
end
def self.elligible_to_new_validation?(record)
return false if !strict_validation_enabled?
return false if (record.created_at || Time.now) < date_since_strict_email_validation
return false if (record.created_at || Time.zone.now) < date_since_strict_email_validation
true
end
@ -26,6 +34,4 @@ class StrictEmailValidator < ActiveModel::EachValidator
rescue
DateTime.new(1789, 5, 5, 0, 0) # french revolution, ds was not yet launched
end
end