Back to Devise Wiki

How To: Sign In As Another User If You Are An Admin

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

latest1.4 KB
Original Source

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:

ruby
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|https://github.com/ankane/pretender]] gem, which has been known to work on projects where the code above and [[switch_user|https://github.com/flyerhzm/switch_user]] have failed.