Reputation: 48453
I am using Devise for authentication. I want to have users the ability to change their passwords - so I have added this action to my controller:
def update_password
if current_user.update_with_password(devise_parameter_sanitizer.sanitize(:account_update))
sign_in(current_user, bypass: true)
redirect_to settings_path, notice: "Your password has been updated!"
else
current_user.errors.each do |err|
puts "-> #{err.inspect}"
end
redirect_to settings_path, alert: "Problem: #{current_user.errors.inspect}"
end
end
If a user enters the right current password and the new password (plus its confirmation), then the password is changed - that's good.
However, when there's a problem, such as the new password + its confirmation is not matched, or if the entered current password is not correct, or if eg. the new password is not long enough - then it fails, that's good as well.
However, I'd want to display to users why the password has not been changed - how do I find out the reason for not changing the password? Where do I find the error messages?
Thank you in advance.
Upvotes: 1
Views: 677
Reputation: 1828
you will need to validate some of these on the controller level and manually like the confirmation of the new password and the old password with a simple if the did not match
then redirect_back and flash and error (it would be nice also to have a small JS script to evaluate this instead of waiting for a request to come to the controller but also keep the validation in the controller)
and for the old password confirmation, you will need to use Devise::Encryptor.compare(klass, hashed_password, password)
and also raise a error manually then go on to storing a new password and check if the record did save normally
def update_password
old_password = devise_parameter_sanitizer.require(:old_password)
new_password = devise_parameter_sanitizer.require(:new_password)
new_password_confirmation = devise_parameter_sanitizer.require(:new_password_confirmation)
if new_password != new_password_confirmation
redirect_to settings_path, alert: "NEW PASSWORD DO NOT MATCH"
end
if Devise::Encryptor.compare(User, current_user.encrypted_password, old_password)
redirect_to settings_path, alert: "SAME OLD PASSWORD ERROR!"
end
if current_user.update_with_password(devise_parameter_sanitizer.sanitize(:account_update))
redirect_to settings_path, notice: "Your password has been updated!"
else
redirect_to settings_path, alert: person.errors.full_messages.to_sentences
end
end
Upvotes: 1