-
Notifications
You must be signed in to change notification settings - Fork 5.5k
How To: # as another user if you are an admin
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:
- switch_user by flyerhzm
- any_login by igorkasyanchuk
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.