Sunday, September 4, 2011

rails, devise and how to edit user account profile without providing a password

There are several options on the wiki to update an account information without providing a password

https://github.com/plataformatec/devise/wiki/How-To%3a-Allow-users-to-edit-their-account-without-providing-a-password

This is due to the fact that devise is asking for the current password for all profile changes. The wiki makes changes to remove password fields or the current password from the form.

The workflow I was looking for was to allow the user to change details such as first and last name without a password. Only when the current password is change is a password required.

Solution:
rails 3.1
devise 1.4.4
From the Gem
/gems/devise-1.4.4/lib/devise/models/database_authenticatable.rb

copy the method update_with_password and add it to your user.rb model (or whatever model you're using to store account information)

      def update_with_password(params={})
        current_password = params.delete(:current_password)

        if params[:password].blank?
          params.delete(:password)
          params.delete(:password_confirmation) if params[:password_confirmation].blank?
        end

        result = if valid_password?(current_password)
          update_attributes(params)
        else
          self.attributes = params
          self.valid?
          self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
          false
        end

        clean_up_passwords
        result
      end

Next change the line
result = if valid_password?(current_password)
to
result = if params[:password].blank? && if params[:password].blank? || valid_password?(current_password) 

Don't check for current password if password is blank, go ahead and update

2 comments:

TalkingQuickly said...

Really useful post, only tweak for me was making the line

result = if params[:password].blank? || valid_password?(current_password)

(removing the second if)

saved me a lot of time. Many thanks.

James Stubblefield said...

This saved me some time as well. Thank you for posting!