Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

migrating from legacy password to rails devise

I'm migrating from a legacy system that uses simple MD5 unsalted passwords into Devise. While I could roll my own encryptor as recommended on the Devise wiki I actually want to migrate to the bcrypt password mechanism.

This also seems more reasonable than downloading rainbow tables and trying to discover all the plaintext passwords...

So, I'm wondering if there might be any side-effects to the following code, especially around the save! triggering any callbacks that have unintended behavior:

## config/initializers/legacy.rb
require 'bcrypt'
require 'digest/md5'

module Devise
  module Models
    module DatabaseAuthenticatable
      def valid_password?(password)
        if self.legacy_password_hash
          if ::Digest::MD5.hexdigest(password) == self.legacy_password_hash
            ## authenticated; now convert to bcrypt password
            self.password = password
            self.legacy_password_hash = nil
            self.save!
            return true
          else
            ## so that we don't get a bcrypt invalid hash exception
            return false
          end
        else
          return ::BCrypt::Password.new(self.encrypted_password) == "#{password}#{self.class.pepper}"
        end            
      end
    end
  end
end
like image 874
Matt Avatar asked Jan 31 '11 03:01

Matt


1 Answers

Shamelessly stolen from:

http://groups.google.com/group/plataformatec-devise/browse_thread/thread/9dcf87b2225bd11f?pli=1

In short, do not override Devise's default authentication. Just put this method into your authentication model (usually User).

like image 189
dimitarvp Avatar answered Oct 10 '22 00:10

dimitarvp