【问题标题】:Can you check previously used passwords (password history) using Authlogic?您可以使用 Authlogic 检查以前使用的密码(密码历史记录)吗?
【发布时间】:2015-09-08 05:50:42
【问题描述】:

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

【问题讨论】:

标签: ruby-on-rails passwords authlogic


【解决方案1】:

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

$ 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

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

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

最后创建一个名为 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

希望这会有所帮助 快乐黑客

【讨论】: