Devise Forgot Password for logged in user

fiestacasey picture fiestacasey · Jan 23, 2012 · Viewed 9k times · Source

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 with facebook, a fake password is generated for them 2. the user then wants to change their email/name/password, or just use non facebook login

since devise requires a password to change these fields, as it should, the user is unable to modify them

I had thought about just not forcing the password to be set but that doesn't make sense security wise so instead I just display the fields as text and notify the user to follow the 'forgot password' procedure in order to set a password and then they can change the fields

The issue then is that I cannot simply link to this from the user profile since devise will tell the user that they can't do this while already logged in.

So is there a manner of overriding the forgot password or /users/password/edit method so that a logged in user can perform this action as well?

Answer

user3294438 picture user3294438 · Mar 1, 2014

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'}