1
votes

In my app I'm using both the Devise and Reform Gems.

I want to enable a signed in user to very simply change their password by providing their current password, new password and new password confirmation. I have achieved the Password update functionality, but I'm struggling with the :current_password validation ( Wiki used for help).

In my controller I'm using this:

def update_password_self
  if @user.validate( params[:user] )
    @user.save
    # Sign in the user by passing validation in case their password changed
    sign_in @user.model, :bypass => true
    respond_with(@user, :location => user_self_platform_profile_path( id: @user.id, anchor: "#user_self_settings"))
  else
    render "edit_password_self"
  end
end

In my UserForm Form class, I have the following:

property    :current_password,
            validates: {
              presence:                     true,
              validate_this_password:       true
            }

The validate this password is a Custom validator that looks like this:

class ValidateThisPasswordValidator < ActiveModel::EachValidator
 def validate_each(record, attribute, value)
  unless current_user.valid_password?(value)
    record.errors[attribute] << (options[:message] || "password not right.")
  end
 end
end

The current_user object is not made available to a form object, and thus returning an error. What is the best way to achieve the above using these two GEMS?

Thanks

1

1 Answers

1
votes

I have figured out the solution. In case anybody else runs into this issue, here is the solution:

class ValidateThisPasswordValidator < ActiveModel::EachValidator
 def validate_each(record, attribute, value)
  unless User.find(record.id).valid_password?(value)
    record.errors[attribute] << (options[:message] || "password not right.")
  end
 end
end