Brcrypt authenticate method not working with already brcypt value

88 Views Asked by At

I have a User Model with encryption using brcypt gem.

However, when I am using the following code it is returning false as result.

User.find(117).try(:authenticate ,User.find(117).password_digest)

But below mentioned command works fine:

User.find(117).try(:authenticate ,"password")

It returns true.

So how can I achieve the first conditions when I need to validate the password already stored in the database.

Any help would be appreciated!!

2

There are 2 best solutions below

1
On

In you first line you pass the digested password, that (depending on your implementation or gem you are using) should be an one-way encrypted string from the original password. You have no way to verify this digest without the original password.

While try is a great thing, it hides away all useful errors you could get. Your code would be better if you split up finding the user and authenticating the password.

0
On

Try the below instead:

User.find(117).try(:authenticate ,User.find(117).password)

You never directly call password_digest on user.

password_digest is only used when setting the field in the database and the type on the form in the view.

For all other purposes call the ".password" attribute on the user.