2014-04-06 40 views
4

當我創建的用戶(在西納特拉),我這樣做爲什麼BCrypt無法在此情況下進行身份驗證?

require 'Bcrypt' 

post '/users' do 
    @user = User.new(params[:user]) 
    @user.password_hash = BCrypt::Password.create(params[:password]) 
    p @user.password_hash == params[:password]    # this prints TRUE! 
    @user.save! 
    session[:user_id] = @user.id 
    redirect '/' 
end 

然後當我嘗試驗證相同的用戶我得到這個

post '/sessions' do 
    @user = User.find_by_email(params[:email]) 
    p @user.id            # prints 14 
    p @user.password_hash          # prints correct hash 
    p @user.password_hash.class        # prints String 
    p BCrypt::Password.new(@user.password_hash).class   # prints BCrypt::Password 
    p params[:password]          # prints "clown123" 
    p BCrypt::Password.new(@user.password_hash) == params[:password] # prints FALSE! 

    # redirect '/' 
end 

什麼突破? BCrypt文檔(不使用數據庫)中給出的示例每次都有效。 可以在我的分貝(postgres)的東西改變密碼?哈希?使用

的最新版本bcrypt的,和Ruby 1.9.3(我試過紅寶石2.0和行動,以及具有相同的結果)

回答

1

什麼DB列的類型是您使用?您可以嘗試不使用數據庫,而是使用會話。以下正確的工作對我來說,

# app.rb 

require 'sinatra' 
require 'bcrypt' 

enable :sessions 

get '/user' do 
    session[:password_hash] = BCrypt::Password.create(params[:password]) 
    return 'success' 
end 

get '/session' do 
    result = BCrypt::Password.new(session[:password_hash]) == params[:password] 
    return "Result: #{result}" 
end 
在瀏覽器

然後,

http://localhost:4567/user?password=secret 

# => success 

http://localhost:4567/session?password=secret 

# => Result: true 

http://localhost:4567/session?password=invalid 

# => Result: false 

如果這樣的作品,再試一次引入DB,

require 'sinatra' 
require 'bcrypt' 

# your postgres config here... 

get '/pg-user' do 
    user = User.new(password_hash: BCrypt::Password.create(params[:password])) 
    user.save! 
    return 'success' 
end 

get '/pg-session' do 
    user = User.last 
    result = BCrypt::Password.new(user.password_hash) == params[:password] 
    return "Result: #{result}" 
end 
+0

感謝 - 原來我的PARAMS是從我的註冊表中以奇怪的方式進入,問題不在於我的數據庫 – dwilbank

相關問題