Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise authentication logs in after password change

Devise authentication gem in Rails.

How to prevent automatic logging in after password change by "forgot password" link?

Ideally it would be nice to display the page with message "New password has been saved".

like image 921
Paul Avatar asked Feb 20 '23 10:02

Paul


2 Answers

You will need to override Devise's passwords_controller which you can see the default methods for here. First, create your own controller which will inherit from the Devise controller:

class User::PasswordsController < Devise::PasswordsController

Once you have your controller ready, add in all of the other methods that you do not want to override, and simply call super inside of them. This will be the new, edit, and create methods. Also don't forget to add the protected after_sending_reset_password_instructions_path_for(resource_name) method.

The method that you are concerned with overriding is the update action.

def update
  self.resource = resource_class.reset_password_by_token(resource_params)

  if resource.errors.empty?
    flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
    set_flash_message(:notice, "Your flash message here")
    redirect_to new_user_session_path
  else
    respond_with resource
  end
end

All we change here is to remove the line to sign in the user with a redirect to the sign in page, and then set our custom flash message.

Lastly, you have to tell devise to use your new controller, so in routes.rb change devise_for :users to:

devise_for :users, :controllers => { :passwords => 'users/passwords' }

And that should do it.

like image 50
janders223 Avatar answered Feb 23 '23 05:02

janders223


Here's an update based on 3.1.1 of devise

class Users::PasswordsController < Devise::PasswordsController

 def new
   super
 end

 def edit
   super
 end

 def create
   super
 end

 #override this so user isn't signed in after resetting password
 def update
    self.resource = resource_class.reset_password_by_token(resource_params)

    if resource.errors.empty?
      resource.unlock_access! if unlockable?(resource)
      flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
      set_flash_message(:notice, flash_message) if is_navigational_format?

      respond_with resource, :location => after_resetting_password_path_for(resource)
    else
      respond_with resource
    end

  end

protected

   def after_resetting_password_path_for(resource)
     new_session_path(resource)
   end

end

like image 26
jschweitzer Avatar answered Feb 23 '23 06:02

jschweitzer