Rails Devise Legacy Users from CakePHP

2019-07-16 14:53发布

问题:

I recently got Devise working. New users sign in, sign up, logout etc etc just fine. Old users however have an issue. I have gotten it to a point where I get a 401 unauthorized, which seems to me that the hash is just incorrectly being created when signing in and of course not matching correctly.

My user model:

class User < ActiveRecord::Base
  require "digest/sha1"
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :encryptable, :encryptor => :old_cakephp_auth

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
  has_many :events
end

Cakephp uses sha1, but I don't know the specifics of how it does things. This obviously doesn't work, which is why I am here:

require "digest/sha1"

module Devise
  module Encryptors
    class OldCakephpAuth < Base
      def self.digest(password, stretches, salt, pepper)
        Digest::SHA1.hexdigest("#{salt}#{password}")
      end
    end
  end
end

I got that from the how to add a custom encryptor example. They had this:

Digest::SHA1.hexdigest("--#{salt}--#{password}--")

That didn't work either. Anyone have any ideas?

回答1:

I saw a variation of this on the create your own custom encryptor wiki. I don't know how I didn't see it before. Perhaps someone updated it recently.

Place the following in your user model. It should overwrite valid password from devise:

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

You need to make sure to fill in the password salt you used in cake into all legacy user's rows. You also need to change password to encrypted password according to devise's instructions.

I feel like I may need to add a way encrypt from user model as well for new users. Or perhaps the custom encryptor I created handles that aspect.