Skip to content

How To: Sign in as another user if you are an admin

Igor Kasyanchuk edited this page Mar 17, 2019 · 9 revisions

This is a useful administration feature I've seen on a few apps where you can quickly "become" one of the users to see what their profile and screens look like.

The implementation is simple but it took me a while to find out how to do it, so I'm recording it here:

class AdminController < ApplicationController
  before_filter :authenticate_user!
  
  def become
    return unless current_user.is_an_admin?
    sign_in(:user, User.find(params[:id]))
    redirect_to root_url # or user_root_url
  end
end

If you want to ensure that last_sign_in_at and current_sign_in aren't updated when becoming the user, you can replace sign_in(:user, User.find(params[:id])) with bypass_sign_in(User.find(params[:id])) in the example above. The bypass_sign_in method bypasses warden callbacks and stores the user straight in the session.

For a slightly more advanced & customizable implementation of this concept, packaged as a gem, check out:


If you find that the above approaches do not work, there are various other gems to try, including ankane's pretender gem, which has been known to work on projects where the code above and switch_user have failed.

Clone this wiki locally