简体   繁体   中英

check for password when using password_digest rails

So I implemented an auth system on my rails API using the knock and bcript gems. I hence added has_secure_password in my user model and when a new user is created, it has a password_digest attribute in the db.

I am now building the possibility for the end user to change his/her password. For security reasons, I want to ask for the old password, check wether the old password given is the right one, and if so, update the user's password. Otherwise, send an error message.

So here is what I wrote:

def update_password
     @user = User.find(params[:id])
     if params[:password][:oldPassword] === @user.password
       if @user.update(password: params[:password][:newPassword])
         render json: @user
       else
         render json: @user.errors, status: :unprocessable_entity
       end
     else
       render json: {erreur: "the current password is wrong"}, status: :unprocessable_entity
     end
   end

My problem here is: params[:password][:oldPassword] === @user.password to check for current password validity doesn't work: it will always return false .

How can I do this the right way?

有一个方法user.authenticate(pass)

You are comparing the password type against a digested hash, thats causing it to always return false. ie the user types his old password "123456", but the system cant access that string, when it queries the database it return something like "$2a$12$.FMAPyhKwOyg.bHti8aFzuOcBw1w2ho1HI5IOloa4vlSMnAMMNtJC". Thats a security measure caused by bcript. To check the it you must use the .authenticate(:password) method, it will encrypt "123456" into a hash and then match it against the database.

Maybe is not what you are looking for but I ran into a similar issue a few months ago, a solution to compare properly those passwords is to use bcrypt as below:

BCrypt::Password.new(new_password) == (user.password)

The order of the elements in the expression is important because Rails set the correct comparer, meaning that the bcrypt instance needs to be on the left.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM