Password encryption problem in Rails Devise gem

最后都变了- 提交于 2019-12-21 06:19:22

问题


I am now currently changed to use the Gem Devise for user authentication. But I don't know how to match the encryption!

I knew that we could write a new encryptor and assign it in initializers, but the point is the encryptor accepts 4 arguments only (password, stretches, salt, pepper). But in my case, I do included the user's email and a customized salt in the encryption.

Is it possible to pass the user's email and customized salt into the encryptor?

ps. I am using database_authenticatable


回答1:


It's sad that no one answered my question......

However, I think I've found the answer, although it's not as pretty as I imagined.

First, create the encryption class in the initializers:

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

      def self.salt(email)
        Digest::SHA1.hexdigest("#{Time.now}-----#{email}")
      end
    end
  end
end

Secondly, overwrite some methods in the User model:

# overwrite this method so that we call the encryptor class properly
def encrypt_password
  unless @password.blank?
    self.password_salt = self.class.encryptor_class.salt(email)
    self.encrypted_password = self.class.encryptor_class.digest(@password, self.password_salt)
  end
end

# Because when the database_authenticatable wrote the following method to regenerate the password, which in turn passed incorrect params to the encrypt_password, these overwrite is needed!
def password=(password)
  @password = password
end
def password_digest(pwd)
  self.class.encryptor_class.digest(pwd, self.password_salt)
end

And finally, we have to teach when to encrypt the password:

before_save :encrypt_password



回答2:


I'm not sure how old this is, but this seems like a better supported way of doing it: http://presentations.royvandewater.com/authentication-with-devise.html#9



来源:https://stackoverflow.com/questions/3492033/password-encryption-problem-in-rails-devise-gem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!