简体   繁体   中英

How to change password without current password in devise?

I am using devise for authentication and i have a role for each user and i allow the user with admin role to create new user and i want the admin user to edit the password for the rest of user if they forgot their password. But i cannot able to change the password without current password in edit. So how can i allow the admin user to change the password by editing the users password and save as we do for the rest of the values.

Since update_without_password still requires current_password to update the password, you will have to have an update like this:

  def update
    # required for settings form to submit when password is left blank
    if params[:user][:password].blank?
      params[:user].delete("password")
      params[:user].delete("password_confirmation")
    end

    @user = User.find(current_user.id)
    if @user.update_attributes(params[:user])
      set_flash_message :notice, :updated
      # Sign in the user bypassing validation in case his password changed
      sign_in @user, :bypass => true
      redirect_to after_update_path_for(@user)
    else
      render "edit"
    end
  end

This example is meant for updating the current user (including user's password), but you can modify it to fit your needs.

@user.update_attributes(password: params[:user][:password])

There is a method built in to devise called update_without_password .

Here's what I'm using in my update method:

 # PUT /manage_users/1
  # PUT /manage_users/1.json
  def update
    @user = User.find(params[:id])
    able_to_edit_profile?

    # required for settings form to submit when password is left blank
    if params[:user][:password].blank?
      params[:user].delete("password")
      params[:user].delete("password_confirmation")
    end

    respond_to do |format|
      if @user.update_attributes(params[:user])
        @user.save        

        # sign the user in with their new password so it doesn't redirect to the login screen
        sign_in @user, :bypass => true

        format.html { 
          flash[:notice] = 'User was successfully updated.'
          redirect_to session.delete(:return_to)
        }
        format.json { head :no_content }
      else
        format.html { render action: "edit", notice: 'Error updating user.' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

private 

  # If the user is not an admin and trying to edit someone else's profile, redirect them
  def able_to_edit_profile?
    if !current_user.try(:admin?) && current_user.id != @user.id
      flash[:alert] = "That area is for administrators only."
      redirect_to :root
  end
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM