您可以使用 Authlogic 检查以前使用过的密码(密码历史记录)吗?

Aar*_*son 4 passwords ruby-on-rails authlogic

我在 rails 应用程序中使用Authlogic进行密码验证。我想确保用户不使用过去 10 个使用过的密码中的任何一个。Authlogic 是否允许您这样做,或者您必须手动滚动某些东西?

MZa*_*oza 5

为确保您的用户不会重复密码,您将需要密码历史记录

$ rails g migration CreatePasswordHistory

 class CreatePasswordHistories < ActiveRecord::Migration
  def self.change
    create_table(:password_histories) do |t|
      t.integer :user_id
      t.string  :encrypted_password
      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

现在您可以更新用户模型以将密码保存到密码历史模型中,例如:

class AdminUser < ActiveRecord::Base
  include ActiveModel::Validations
  has_many :password_histories
  after_save :store_digest
  validates :password, :unique_password => true
  ...

  private
  def save_password_history
    if encrypted_password_changed?
      PasswordHistory.create(:user => self, :encrypted_password => encrypted_password)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

最后创建一个名为 unique_password_validator 的模型

require 'bcrypt'
class UniquePasswordValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.password_histories.each do |password_history|
      bcrypt = ::BCrypt::Password.new(password_history.encrypted_password)
      hashed_value = ::BCrypt::Engine.hash_secret(value, bcrypt.salt)
      record.errors[attribute] << "has been used previously." and return if hashed_value == password_history.encrypted_password
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

希望这有助于Happy Hacking