require "strong_password" module ThinkFeelDoEngine module Concerns # validates passwords. module ValidatePassword WEAK_PASSWORD_MESSAGE = "is too weak" extend ActiveSupport::Concern included do before_validation :contains_integer, :contains_lowercase_letter, :contains_uppercase_letter, :repeating_characters, on: [:create, :update], if: :password_exists_without_message? validates :password, password_strength: { extra_dictionary_words: :extra_words, use_dictionary: true, min_entropy: ThinkFeelDoEngine:: PasswordValidator::VALID_ENTROPY, message: WEAK_PASSWORD_MESSAGE }, if: :password_exists_without_message? end private def contains_integer set_error_on_password unless password =~ /[0-9]/ end def contains_lowercase_letter set_error_on_password unless password =~ /[a-z]/ end def contains_uppercase_letter set_error_on_password unless password =~ /[A-Z]/ end def email_prefix @email_prefix ||= email[/[^@]+/] end def extra_words [email_prefix, email_prefix.reverse] if email.present? end def password_exists_without_message? password.present? && !errors.full_messages.include?("Password #{WEAK_PASSWORD_MESSAGE}") end def repeating_characters set_error_on_password if password =~ /(.)\1\1/ end def set_error_on_password errors.add(:password, WEAK_PASSWORD_MESSAGE) end end end end