How to Impersonate a User in a Rails Saas Application?
“Impersonate” means a person imitates the behavior or actions of another person. It is very common in SaaS applications that, your support staff need to impersonate users and perform some operations on behalf of impersonated user.
The support staff/admin should be able to log into the other user’s account seamlessly without using credentials of that user, pretending as the normal user.
Here comes the ‘pretender‘ gem for serving the purpose beautifully. It is really easy to avail impersonating feature in any ruby on rails application with minimum configuration. As per the pretender README,
So here are the steps to integrate:
- Add the gem in your gemfile & run bundle install.
- Add the following in Application Controller:
Somewhere in your accessible view area, list all users and put a link against each user with following helper:
= link_to "Impersonate", start_impersonate_path(user_id: user.id)
Ensure this path in configure in routes.rb
scope '/admin' do
get 'start_impersonate' => 'admin#start_impersonate', as: 'start_impersonate'
get 'stop_impersonating' => 'admin#stop_impersonating', as: 'stop_impersonate'
Create impersonating actions to start impersonating and stop impersonating like below in Admin Controller:
user = User.find_by(id: params[:user_id])
impersonate_user(user) if user.present?
When start impersonate method executes, admin will becomes true_user and the impersonated user will becomes current_user. You would like to have indication of which user you are impersonating in UI somewhere. So add following lines in application layout(header)
<% if current_user != true_user %>
You (<%= true_user.name %>) are signed in as <%= current_user.name %>
<%= link_to "Back to admin", stop_impersonating_path %>
<% end %>
This helper script would generate a link to stop impersonating with showing which user is impersonated.
We were using devise-invitable gem to invite other users in the application. So, when the impersonated user invites some other user, the invited_by_id of admin user(true_user) gets saved in the database for that user instead of impersonated user.
To fix this, add following method in the application controller to make it work.
This method returns the original user and so the invited_by_id column would now have original user’s reference id and not of admin user’s.
At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management