我正在mvc框架中工作,我想防止用户从最后4个密码中创建密码。
到目前为止,这是我所做的事情,实际上,我遵循的是github某人的代码,但似乎他没有提到encrypted_password_changed
函数和encrypted_password
函数。
密码历史记录表
class CreatePasswordHistories < ActiveRecord::Migration
def self.up
create_table(:password_histories) do |t|
t.integer :user_id
t.string :encrypted_password
t.timestamps
end
end
def self.down
drop_table :password_histories
end
end
用户模型
class User < ApplicationRecord
include ActiveModel::Validations
has_many :password_histories
after_save :store_digest
validates :password, :unique_password => true
private
def store_digest
if encrypted_password_changed?
PasswordHistory.create(:user => self, :encrypted_password => encrypted_password)
end
end
end
自定义验证器
require 'bcrypt'
class UniquePasswordValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.password_histories.each do |ph|
bcrypt = ::BCrypt::Password.new(ph.encrypted_password)
hashed_value = ::BCrypt::Engine.hash_secret([value, Devise.pepper].join, bcrypt.salt)
record.errors[attribute] << "has been used previously." and return if hashed_value == ph.encrypted_password
end
end
end