How to check current password in Rails (Devise gem)?
-
03-07-2021 - |
Question
I'm failing to check current password using jQuery validation. I'm using Devise gem and jQuery validation. Firebug says:
the problem is in my controller :
def checkpass
user = User.find_by_email(params[:user][:email])
respond_to do |format|
if user && user.authenticate(params[:user][:password])
format.json { render :json => @user }
end
end
with this code Firebug gives me error
406 Not Acceptable
end
example of checkemail uniqueness action:
def checkemail
@user = User.find_by_email(params[:user][:email])
respond_to do |format|
format.json { render :json => !@user }
end
end
My js:
$("#edit_password").validate({
"user[current_password]":{
required: true,
minlength: 6,
remote: {
url: "http://127.0.0.1:3000/checkpass"
}
...
})
and HTML:
<input type="password" size="30" name="user[current_password]" id="user_current_password" class="valid">
Can someone suggest how to do it ?
Solution
in the controller in function check_pass
user = User.find_by_email(params[:user][:email])
respond_to do |format|
if user && user.authenticate(params[:user][:password])
format.json { render :json => @user }
end
end
OTHER TIPS
I am using rails version 4 and when I tried doing user.authenticate I got error saying unknown methods, so I found the other method for checking if password is valid,
valid_password?(current_password)
I thought to share it so it might help someone else as well.
Password is not stored in plain text format it's a salted hash,so user can't find using password.
You can authenticate password is valid or not so salted hash work like
crypted string = plaintext(password)+hashing algo(encrypt)
some random string(salt) +crypted string then checked for match You can use
warden.authenticate
orauthenticate
(check docs) method on user to verify password