2014-10-22 88 views
0

爲了安全地存儲我的用戶密碼,我試圖在我的Sinatra/Ruby應用程序中使用BCrypt。紅寶石BCrypt密碼比較返回不正確的評估

以下代碼是我的用戶模型。

require 'mongo_mapper' 
require 'bcrypt' 

# User model 
class User 
    include MongoMapper::Document 
    include BCrypt 

    key  :email,   String,   length: 6..50,  unique: true 
    key  :password,  String 
    key  :password_hash, String 

    def password 
     @password ||= Password.new(password_hash) 
    end 

    def password=(new_password) 
     @password = Password.create(new_password) 
     self.password_hash = @password 
    end 

    def self.authenticate(requested_email, requested_password) 
     u = self.find_by_email(requested_email) 
     u if u && u.password_hash == requested_password 
    end 
end 

# Test user account 
if User.count == 0 
    user = User.new(email: "[email protected]") 
    user.password = "admin" 
    user.save 
end 

當我調用如下所示的驗證方法:User.authenticate("[email protected]", "admin")時,代碼返回false。我確定用戶存在。

編輯: u.password == requested_password返回false以及

爲什麼會發生這種情況,即使被傳遞給方法的值是有效的,正確的?

回答

0

創建一個名爲secret的密鑰,刪除密碼和password_hash。

你的代碼更改爲:

def password=(password) 
    self.secret = BCrypt::Password.create(password) 
end 

def password 
    return BCrypt::Password.new(secret) if self.secret 
    nil 
end