为确保您的用户不会重复密码,您需要密码历史记录
$ 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
希望这会有所帮助
快乐黑客