Rails Devise gem中的密码加密问题

Pet*_*ong 2 gem ruby-on-rails devise

我现在更改为使用Gem Devise进行用户身份验证.但我不知道如何匹配加密!

我知道我们可以编写一个新的加密器并将其分配给初始化器,但重点是加密器只接受4个参数(密码,延伸,盐,胡椒).但就我而言,我确实在加密中包含了用户的电子邮件和自定义的盐.

是否可以将用户的电子邮件和自定义盐传递给加密器?

PS.我正在使用database_authenticatable

Pet*_*ong 9

很遗憾没有人回答我的问题......

但是,我想我找到了答案,虽然它没有我想象的那么漂亮.

首先,在初始值设定项中创建加密类:

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
Run Code Online (Sandbox Code Playgroud)

其次,覆盖User模型中的一些方法:

# 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
Run Code Online (Sandbox Code Playgroud)

最后,我们必须教授何时加密密码:

before_save :encrypt_password
Run Code Online (Sandbox Code Playgroud)