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

rantaoca edited this page Jan 15, 2015 · 6 revisions
Clone this wiki locally

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

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 sign_in(:user, User.find(params[:id]), { :bypass => true }) in the example above. The :bypass option 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 flyerhzm's switch_user project.