I am using Authlogic in a rails app for password validation. I would like to ensure that the user doesn't use any of the past 10 used passwords. Does Authlogic allow you to do that, or do you have to hand roll something?
Asked
Active
Viewed 1,418 times
4
-
You could use devise gem for authentication and devise have this wiki [How To: Disallow previously used passwords](https://github.com/plataformatec/devise/wiki/How-To:-Disallow-previously-used-passwords) – rails_id Jun 22 '15 at 17:32
1 Answers
6
To make sure that your users dont repeat passwords you will need a password history
$ 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
Now you can update the users model to save the password to the password history model something like:
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
Finally create a model called 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
Hope this helps Happy Hacking

MZaragoza
- 10,108
- 9
- 71
- 116