Force Restful Authentication to login as a specific user (an admin function)?
-
13-09-2019 - |
Question
I'm using Restful Authentication and I'd like to be able to log in as different users on our site to investigate issues they may be having ("see what they see"). Since all passwords are encrypted I obviously can't just use their passwords.
So, how can I force a session to be logged in as a specific user?
Solution
In your
sessions_controller
add actionimpersonate
like this:def impersonate user = User.find(params[:id]) logout_killing_session! self.current_user = user flash[:notice] = t(:logged_in) redirect_to root_url end
Then in your routes extend session resource with the member
impersonate
:map.resource :session, :member => {:impersonate => :post}
Finally, somewhere in your admin views add a button to each user called "Impersonate". It will have to look something like this (assuming that user is in local variable
user
):<%= button_to "Impersonate", impersonate_session_path(:id => user.id) %>
Using this approach you also avoid overriding any tracking data such as time of the last login, etc.
P.S. Don't forget to require admin for impersonate
action in sessions controller.
OTHER TIPS
Simply override session[:user_id]
with the id of the user you want to be. One easy way is to have the user log in as an admin and then give them a drop-down of usernames. When they submit the form, have the controller set session[:user_id]
and then reload current_user
. The admin will then 'become' that user.