0

我正在实施一个验证方案,并且正在使用 bcrypt-ruby gem。

require 'bcrypt'

    class User < ActiveRecord::Base

      include BCrypt

      attr_accessor :password

      attr_accessible :name, :email, :password, :password_confirmation

      validates :password, :presence => true, :on => :create,
                           :confirmation => true,
                           :length => {:within => 6..12}

     before_save :encrypt_password

      def has_password?(submitted_password)
      self.encrypted_password == submitted_password # this calls a method in bcrypt    

    # File lib/bcrypt.rb, line 171
    #     def ==(secret)
    #       super(BCrypt::Engine.hash_secret(secret, @salt))
    #     end

      end

    private

      def encrypt_password

           self.encrypted_password = Password.create(password, :cost => 5)  
       end
    end

现在在控制台中我创建了一个新用户

>> user = User.create!(:name => "test", :email => "test@test.com", :password => "foobar", :password_confirmation => "foobar")

=> #<User id: 1, name: "test", email: "test@test.com", created_at: "2011-06-23 05:00:00", updated_at: "2011-06-23 05:00:00", encrypted_password: "$2a$10$I7Wy8NDMeVcNgOsE3J/ZyubiNAESyxA7Z49H4p1x5xxH...">

如果我检查密码是否有效,我会执行以下操作:

>> user.has_password?("foobar")
=> true

但如果我从数据库中获取用户,它会失败:

user = User.find(1)
user.has_password?("foobar")
=> false

为什么会发生这种情况,我该如何实施 bcrypt 来完成这项工作?

先感谢您。

4

2 回答 2

0

我的猜测是,由于 encrypted_pa​​ssword 作为字符串而不是 BCrypt::Password 存储在数据库中,因此您不是调用 BCrypt 的 ==,而是调用 String 的 ==。您必须围绕字符串哈希值实例化密码的实例。那将是我要看的地方。

于 2011-06-23T06:01:20.033 回答
0

这里所述,您必须使用 Bcrypt 的密码类来利用==

def has_password?(submitted_password)
  Bcrypt::Password.new(self.encrypted_password) == submitted_password
end
于 2019-04-08T10:20:43.207 回答