ruby-on-railsauthenticationdeviselogoutpassword-recovery

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".


Solution

  • 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.