Why can't BCrypt authenticate in this context?

when I create users (in sinatras), I do it

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

then when I try to check the same user, I get this

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

What is broken? The example provided in the BCrypt docs (which does not use the database) works every time. Can something in my db (postgres) change the hash password?

using the latest version of bcrypt and ruby ​​1.9.3 (I tried ruby ​​2.0 and also with the same results)

+4
source share
1 answer

What type of DB column are you using? You can try without a database and use sessions instead. Worked right for me

# 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

Then in the browser

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

# => success

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

# => Result: true

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

# => Result: false

If this works, try entering the database again,

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
+1

Source: https://habr.com/ru/post/1535256/


All Articles