Require password only when changing the password.

I have a registration / editing form that displays through Devise::RegistrationsControllerin my application. Now that it works, you must provide your current password when making any changes to the form. I want it to work, so it current_passwordis only required when updating the field password... or you should repeat "new_password" as a means of confirmation. I did some reading in the Devise Wiki, basically the following links, and they don't seem to list the solution for this. If anyone has an idea of ​​how this can be achieved, I would appreciate it.

https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-password

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

+4
source share
2 answers

So, I was looking for an attempt to solve this problem. I have found a solution.

In my model (user.rb), I added :validatablethe following code snippet:

  devise :omniauthable, :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable,
     :confirmable, :trackable, reset_password_keys:[:email, :company_id],
     request_keys: [:host, :params], omniauth_providers: [:auth0]

Then in my registration controller, I added the following:

def update_resource(resource, params)
  if !params[:password].blank?
    resource.password = params[:password]
    resource.password_confirmation = params[:password_confirmation]
  end

  resource.update_without_password(params)
end

And finally, in my application controller, I added :password_confirmationthe following snippet:

devise_parameter_sanitizer.permit(:account_update) do |u|
  u.permit(:first_name, :last_name, :email, :password, :password_confirmation, :phone_number, :receive_emails,
           location_attributes: [:id, :street, :city, :state, :zip, :country])
end

, , update_resource, . , resource.password password_confirmation . , , current_password , , .

+2

, , , params[:user][:password] params[:user][:password_confirmation]:

, password password_confirmation, update_without_password, user_params, update_attributes

  def update
    ...
    if params[:user][:password].blank? && params[:user][:password_confirmation].blank?
      if @user.update_without_password(user_params)
        flash[:notice] = 'User updated successfully'
        redirect_to some_path
      else
        render :edit
      end
    else
      if @user.update_attributes(user_params)
        # login before update passing the current user
        sign_in(User.find(current_user.id), :bypass => true) 
        flash[:notice] = 'User updated successfully'
        redirect_to some_path
      else
        render :edit
      end
    end
    ...
  end
+2

Source: https://habr.com/ru/post/1674041/


All Articles