From 3428c58b9e2fb2a58366785ad2dc273f8b50192e Mon Sep 17 00:00:00 2001 From: Christophe Robillard Date: Tue, 17 Nov 2020 17:13:31 +0100 Subject: [PATCH] extract password complexity validator for user and superadmin --- app/models/super_admin.rb | 8 +------- app/models/user.rb | 8 +------- app/validators/password_complexity_validator.rb | 7 +++++++ 3 files changed, 9 insertions(+), 14 deletions(-) create mode 100644 app/validators/password_complexity_validator.rb diff --git a/app/models/super_admin.rb b/app/models/super_admin.rb index d9029cbc4..eeb69a255 100644 --- a/app/models/super_admin.rb +++ b/app/models/super_admin.rb @@ -28,13 +28,7 @@ class SuperAdmin < ApplicationRecord devise :rememberable, :trackable, :validatable, :lockable, :async, :recoverable, :two_factor_authenticatable, :otp_secret_encryption_key => Rails.application.secrets.otp_secret_key - validate :password_complexity, if: -> (u) { Devise.password_length.include?(u.password.try(:size)) } - - def password_complexity - if password.present? && ZxcvbnService.new(password).score < PASSWORD_COMPLEXITY_FOR_ADMIN - errors.add(:password, :not_strong) - end - end + validates :password, password_complexity: true, if: -> (u) { Devise.password_length.include?(u.password.try(:size)) } def enable_otp! self.otp_secret = SuperAdmin.generate_otp_secret diff --git a/app/models/user.rb b/app/models/user.rb index 1582b6a6c..9ed96c681 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -54,13 +54,7 @@ class User < ApplicationRecord before_validation -> { sanitize_email(:email) } - validate :password_complexity, if: -> (u) { u.administrateur.present? && Devise.password_length.include?(u.password.try(:size)) } - - def password_complexity - if password.present? && ZxcvbnService.new(password).score < PASSWORD_COMPLEXITY_FOR_ADMIN - errors.add(:password, :not_strong) - end - end + validates :password, password_complexity: true, if: -> (u) { u.administrateur.present? && Devise.password_length.include?(u.password.try(:size)) } # Override of Devise::Models::Confirmable#send_confirmation_instructions def send_confirmation_instructions diff --git a/app/validators/password_complexity_validator.rb b/app/validators/password_complexity_validator.rb new file mode 100644 index 000000000..a915a8575 --- /dev/null +++ b/app/validators/password_complexity_validator.rb @@ -0,0 +1,7 @@ +class PasswordComplexityValidator < ActiveModel::EachValidator + def validate_each(record, attribute, value) + if value.present? && ZxcvbnService.new(value).score < PASSWORD_COMPLEXITY_FOR_ADMIN + record.errors.add(attribute, :not_strong) + end + end +end