"BCrypt::Errors::InvalidHash" when trying to sign in
This means that the hash stored in password_digest
is not a valid BCrypt hash (including if the field is empty).
Based on the comments, it looks like you just created the user at a time the has_secure_password
wasn't there, so the password digest never got stored. Look in the database, you'll probably see that password_digest
is empty for that user. Remove the user from the database and re-create with your new working code and it should work.
While discussing with in the comments though, I made an (incorrect) guess about why the passwords would be wrong, and I already wrote up the explanation. So here it is for any future visitor that does have this problem, even though it doesn't apply directly here:
This typically happens when you switch from using SHA1 or another algorithm to BCrypt but fail to re-hash the passwords in BCrypt. Since you don't have access to the original passwords (or at least you shouldn't...), it's a bit ugly to switch because you have to use both BCrypt and the original authentication scheme. For example, if you were using SHA1 before and now use BCrypt, you have to treat the SHA1 password hash as the plain text password for BCrypt input. For example, you might create a BCrypt digest like this:
sha1_password = Digest::SHA1.hexdigest("#{salt}#{real_password}")
self.password_digest = BCrypt::Password.create(sha1_password).to_s
Then, you can create bcrypt password_digests based on the sha1 password hashes that you do have access to.
You would authenticate like this:
sha1_password = Digest::SHA1.hexdigest("#{salt}#{attempted_password}")
BCrypt::Password.new(self.password_digest) == sha1_password
I used SHA1 in the above examples, but this will work for other hashing algorithms as well.
I already had live users, and likewise already saved unencrypted passwords into the database. Once I started using bcrypt, it was expecting an encrypted password, and when it didn't find it, it produced this error.
Therefore, I added this rescue to catch the error and prompt the legacy users to reset their password:
begin
# your code that attempts to login the user
rescue BCrypt::Errors::InvalidHash
flash[:error] = 'We recently adjusted the way our passwords are stored. Please click the "forgot username or password?" link to re-establish your password. Thank you for your understanding!'
redirect_to password_resets_url
end
Hope this helps.