discourse/lib/validators/password_validator.rb
Alan Guo Xiang Tan e97ef7e9af
FEATURE: Allow site admin to mark a user's password as expired (#27314)
This commit adds the ability for site administrators to mark users'
passwords as expired. Note that this commit does not add any client side
interface to mark a user's password as expired.

The following changes are introduced in this commit:

1. Adds a `user_passwords` table and `UserPassword` model. While the
   `user_passwords` table is currently used to only store expired
   passwords, it will be used in the future to store a user's current
   password as well.

2. Adds a `UserPasswordExpirer.expire_user_password` method which can
   be used from the Rails console to mark a user's password as expired.

3. Updates `SessionsController#create` to check that the user's current
   password has not been marked as expired after confirming the
   password. If the password is determined to be expired based on the
   existence of a `UserPassword` record with the `password_expired_at`
   column set, we will not log the user in and will display a password
   expired notice. A forgot password email is automatically send out to
   the user as well.
2024-06-04 15:42:53 +08:00

36 lines
1.5 KiB
Ruby

# frozen_string_literal: true
class PasswordValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return unless record.password_validation_required?
if value.nil?
record.errors.add(attribute, :blank)
elsif value.length < SiteSetting.min_admin_password_length &&
(record.admin? || is_developer?(record.email))
record.errors.add(attribute, :too_short, count: SiteSetting.min_admin_password_length)
elsif value.length < SiteSetting.min_password_length
record.errors.add(attribute, :too_short, count: SiteSetting.min_password_length)
elsif record.username.present? && value == record.username
record.errors.add(attribute, :same_as_username)
elsif record.name.present? && value == record.name
record.errors.add(attribute, :same_as_name)
elsif record.email.present? && value == record.email
record.errors.add(attribute, :same_as_email)
elsif record.confirm_password?(value)
record.errors.add(attribute, :same_as_current)
elsif record.password_expired?(value)
record.errors.add(attribute, :same_as_previous)
elsif SiteSetting.block_common_passwords && CommonPasswords.common_password?(value)
record.errors.add(attribute, :common)
elsif value.chars.uniq.length < SiteSetting.password_unique_characters
record.errors.add(attribute, :unique_characters)
end
end
def is_developer?(value)
Rails.configuration.respond_to?(:developer_emails) &&
Rails.configuration.developer_emails.include?(value)
end
end