Using Crypto::Bcrypt::Password for authentication

#1

I am looking for some pointers on how to use Crypto::Bcrypt::Password for authentication in my web application.

When a user signs up, I store the hashed password of the user in Postgres in a text format. The hash is created using (assume that password is abcd):

 Crypto::Bcrypt::Password("abcd")

Now when the user signs in I am trying to use the following function (currently I have added puts statements for debugging:

def is_email_password_valid(email : String, password : String)
    begin
    puts "Inputs: #{email}, #{password}"
    emaildb, passdb = @conn.query_one("select email, password from users
                            where email = $1",
                            email,
                            as: {String, String})
    rescue ex
        puts ex.message
    else
        puts "#{emaildb}, #{passdb}"
        if password == Crypto::Bcrypt::Password.new(passdb)
            puts "Result: valid email and password"
        else
            puts "Invalid creds!"
        end
    end
end

Even if I enter the correct password, the above is giving my Invalid creds! as output. I am not sure why? Any help about the data format to use and how to compare the two passwords (the plain text entered by the user, and the hashed one in the database) would be appreciated.

Thank you.

#2

Try:

if Crypto::Bcrypt::Password.new(passdb) == password

it seems == is defined on Crypto::Bcrypt::Password but not on String… which makes sense to me, I think using == for this purpose is not a good API design. It should probably be a matches? method on Password or something like that.

If you feel this can be improved, please open an issue in our GitHub repository. Thank you!

2 Likes
#3

Thank you @asterite. That worked! I think you are right. matches? would be better since intuitively, most people would expect == to be commutative.

1 Like
#4

Amber has a good model template implementing bcrypt for authentication. It might be good idea to look over and compare with what you have.

See: https://github.com/amberframework/amber/blob/6c2889bafa57d44d1951a2dec60a519af2fad87a/src/amber/cli/templates/auth/granite/src/models/{{name}}.cr.ecr

1 Like
#5

Thank you, @nsuchy.

1 Like