Mr. bug
Mr. bug

Reputation: 377

Overwrite attribute value on where - Rails 5.1

Hello I need to do like Devise in my own implementation and query User.where(:password => 'password') but password is encrypted and salted. What would be the "rail" way of overwriting this behaivour? I tried with an attr_writter

def password=(pass)
   super(hashpassword(pass))
end

But no success, I still see SELECT 'users'.* FROM 'users' WHERE 'users'.'password' = 'non-salted-password' LIMIT 11

Any suggestion? thank you.

Important

I'm not using devise.

About the solution

The approved solution was to use the native "authenticate" method, I had to change my password field in the database to password_digest and it worked.

Upvotes: 0

Views: 42

Answers (1)

SRack
SRack

Reputation: 12203

There's an authenticate method available for this. This works with has_secure_password.

authenticate is used as follows:

user = User.new(password: 'hash-of-the-password')
user.save
user.authenticate('not-the-password')      # => false
user.authenticate('password') # => user

has_secure_password requires a column called password_digest (though you might be able to override this), which is filled with a hash after someone signs up with a password / password confirmation.

Hope that helps - let me know if you need anything more or have any questions.

Upvotes: 2

Related Questions