Devise Forgot Password for logged in user

后端 未结 3 815
天命终不由人
天命终不由人 2020-12-29 10:25

I\'m wondering if there is a manner of calling the \'forgot password\' procedure without forcing my user to log out

The case I\'m running into is: 1. a user logs in

3条回答
  •  清酒与你
    2020-12-29 11:11

    The reason that you cannot reset password is because the devise tries to authenticate the user with the current session and when succeeded you are automatically redirected to whatever path it is supposed to go to. What you need is to override the edit and update action of passwords controller to make it skip this step.

    Here's the code. In your passwords controller add the following codes (you can ask devise to generate the controllers for you, or you can just create the following controller). The override for update is necessary because otherwise a logged in user will be automatically signout after your reset password. (Or if you want it to be like that you can get rid of the #update override)

    class PasswordsController < Devise::PasswordsController
      # here we need to skip the automatic authentication based on current session for the following two actions
      # edit: shows the reset password form. need to skip, otherwise it will go directly to root
      # update: updates the password, need to skip otherwise it won't even reset if already logged in
      skip_before_filter :require_no_authentication, :only => [:edit, :update]
    
      # we need to override the update, too.
      # After a password is reset, all outstanding sessions are gone.
      # When already logged in, sign_in is a no op, so the session will expire, too.
      # The solution is to logout and then re-login which will make the session right.
      def update
        super
        if resource.errors.empty?
          sign_out(resource_name)
          sign_in(resource_name, resource)
        end
      end
    end
    

    The routes are like the following

    # config/routes.rb
    devise_for :users, :controllers => {:passwords => 'passwords'}
    

提交回复
热议问题