Can you check previously used passwords (password history) using Authlogic?

1.5k views Asked by At

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?

1

There are 1 answers

0
MZaragoza On

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