Skip to content

How To: Allow users to edit their password

plowdawg edited this page Aug 3, 2011 · 54 revisions

We have two options to allow users to edit their password:

  • Use the registerable module, which will give you both sign up and edit user features;
  • Handle your own passwords controller to allow users editing their password.

Example:

class PasswordsController < ApplicationController
  before_filter :authenticate_user!

  def edit
    @user = current_user
  end

  def update
    @user = current_user

    if @user.update_with_password(params[:user])
      sign_in(@user, :bypass => true)
      redirect_to root_path, :notice => "Password updated!"
    else
      render :edit
    end
  end
end

Overriding devise's password controller in your routes file like this:

devise_for :users, :controllers => {:passwords => "passwords"}

You will also need to add the following into routes, so that Rails knows what to do (at least I did, and I had a custom registration controller-Travis):

 resources :passwords

You will then need to create the appropriate views:

Create passwords/edit.html.erb in your view and add and modify the following to your needs:

# views/passwords/edit.html.erb
<div class="section_name">Change Password</div>

<div class="form_div">
<%= form_for(@user, :as => @user, :url => password_path, :html => { :method => :put }) do |f| %>

  <p>
        <%= f.label :current_password %>
        <br />
  	<%= f.password_field :current_password %></p>
  <p><%= f.label :password, "New password" %><br />
  <%= f.password_field :password %></p>

  <p><%= f.label :password_confirmation, "Confirm new password" %><br />
  <%= f.password_field :password_confirmation %></p>

  <p><%= f.submit "Change my password" %></p>
  <%end%>
 </div>

It is also crucial to have attr_accessible: :password, :password_confirmation (in addition to others) in you model. Otherwise, password and confirmation validation will not take place.

I have: attr_accessible :email, :remember_me, :first_name, :last_name, :address_street, :address_city, :address_state, :address_zip, :address_country, :password, :password_confirmation

If you don't want to use update_with_password, which will require to enter the current password, see How To: Allow users to edit their account without providing a password.

Clone this wiki locally