2011-06-23 39 views
0

我正在實施驗證方案,並使用bcrypt-ruby gem。困惑如何使用bcrypt-ruby

需要 '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 => "[email protected]", :password => "foobar", :password_confirmation => "foobar") 

=> #<User id: 1, name: "test", email: "[email protected]", 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才能完成這項工作?

預先感謝您。

回答

0

我的猜測是,因爲encrypted_pa​​ssword作爲字符串存儲在數據庫中,而不是BCrypt :: Password,所以您不會調用進入BCrypt的==,而是調用String的==。你必須在字符串散列值周圍實例化一個密碼實例。那將是我看的地方。

+0

將dbrypt :: Password存儲在db而不是encypted_pa​​ssword是否更好?我怎樣才能做到這一點? – chell