Migrating passwords to Devise

2019-05-16 22:28发布

问题:

I'm migration users database from PHP to Rails. I have already instaled Devise Gem and it is working well now. Also, I have found a hint how to migrate existing users' passwords to Rails I have added old passwords to same encrypted_password field as Devise holds, so when devise fails to auth, checking for old password:

# user.rb      
def valid_password?(password)
  return false if encrypted_password.blank?
  require 'digest/sha1'
  password_salt = 'my_php_framework_salt'
  Devise.secure_compare(Digest::SHA1.hexdigest(password_salt+password), self.encrypted_password)
end

It allows to login with old passwords, but doesn't work with original Devise passwords for new users. I think this valid_password? method should return true for devise passwords. How to fix this?

回答1:

I believe if you manually filled in 'my_php_framework_salt' into the db rows for old users then just used:

self.password_salt instead of password_salt it would work.

As I remember ruby returns the result of the last line in a function. Devise.secure_compare should return a bool, which means valid_password? would return a boolean as well.

In short:

require 'digest/sha1'  

# ...

def valid_password?(password)
  return false if encrypted_password.blank?
  Devise.secure_compare(Digest::SHA1.hexdigest(self.password_salt+password), self.encrypted_password)
end