I make on the site the ability to change the password to the user. The fact is that the password is hashed in the model with the bcrypt jam method built into the model has_secure_password. And when changing the password, the password should be changed only if the old password (which is currently set) coincided with the entered one. And, as we know, the password hash is stored in the database, so a simple comparison of the type

if(@user.password_digest == params(:password)) 

We will not succeed. Actually, hence the question: how to compare the new password value with the hashed password in the database, using has_secure_password in the model?

    1 answer 1

    * yawns * Documentation for has_secure_password see:

     # Schema: User(name:string, password_digest:string) class User < ActiveRecord::Base has_secure_password end user = User.new(name: 'david', password: '', password_confirmation: 'nomatch') user.save # => false, пароль обязателен user.password = 'mUc3m00RsqyRe' user.save # => false, подтверждение пароля отличается user.password_confirmation = 'mUc3m00RsqyRe' user.save # => true user.authenticate('notright') # <- во-от так # => false user.authenticate('mUc3m00RsqyRe') # => user User.find_by(name: 'david').try(:authenticate, 'notright') # => false User.find_by(name: 'david').try(:authenticate, 'mUc3m00RsqyRe') # => user 

    Naturally, the hash comparison with the password does not work, these are different values. Therefore, it should be a хэш_пароля == хэш(пароль) type хэш_пароля == хэш(пароль) . But only in the simplest case.

    • It was about the try method that I didn’t know, thanks for yawning :) - smellyshovel
    • @ Matvey Mamonov um, by. A couple of lines above :) This is for cases where nil can be caught instead of the user. This is a pretty dirty way to get around this, but in very simple cases it will do. - D-side
    • that is, use the 'authenticate' method? I was just looking for an alternative to the 'authenticate?'
    • @ Matvey Mamonov, what do you think he does? :) - D-side
    • Although yes, indeed * facepalm * - smellyshovel