当我创建用户时(在 sinatra 中),我这样做
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)中的某些东西会改变 password_hash 吗?
使用最新版本的 bcrypt 和 ruby 1.9.3(我也尝试过 ruby 2.0 及更高版本,结果相同)
最佳答案
您使用的是什么 DB 列类型?您可以尝试不使用数据库并改用 session 。以下对我来说是正确的,
# 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
如果可行,请再次尝试引入数据库,
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
关于sinatra - 为什么 BCrypt 在这种情况下无法进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22896022/