I'm trying to implement a method to allow password to be changed from another service outside devise anyhow.
# Profile password change
def change_password(oldpass, newpass)
pepper = nil
cost = 10
# Encrypt plain text passwords
encrypt_old = ::BCrypt::Password.create("#{oldpass}#{pepper}", :cost => cost).to_s
# Validate old
if self.encrypted_password == encrypt_old
encrypt_new = ::BCrypt::Password.create("#{newpass}#{pepper}", :cost => cost).to_s
self.encrypted_password = encrypt_new
self.save
else
Logger.new("Wrong old password!")
end
end
It seems i got the password encryption wrong oldpass contains a plain text of old password i need to hash it see if it matches the current password then allow new password to be stored. However all that i'm getting is wrong password.
Reworked:
def change_password(oldpass, newpass)
if valid_password?(oldpass)
password = newpass
save
return true
else
return false
end
end
You don't need to encrypt the password yourself, if you are in the application or in Rails console.
Just update the user following way and Devise will take care of it itself.
user.password = new_password
user.save
Devise will then encrypt the password and store it. You just need to ensure that user.password_confirmation
is nil
. If password_confirmation
is anything else, it will be matched against password
.
EDIT
You can check the existing password with: user.valid_password?(old_password)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With