Adding user impersonation to Rails 8 authentication
Source: Dev.to
Introduction
User impersonation is a powerful feature for SaaS support. It lets you see exactly what a user sees, making it easier to debug issues or provide help.
Quick usage
# Impersonate a user
impersonate! User.find(42)
# Check if you're impersonating
impersonating? # => true
# Get the original user
original_user # => #
# Stop impersonating
unimpersonate!
The impersonation automatically expires after 1 hour (adjustable in the concern).
Routes
# config/routes.rb
Rails.application.routes.draw do
resource :impersonation, only: %w[create destroy]
end
Updating the Current model
# app/models/current.rb
class Current
# Note: Ruby allows logical operators (`&&`, `||`) at the start of a line.
end
Including the concern
Add include Impersonatable to your ApplicationController.
Impersonations controller
# app/controllers/impersonations_controller.rb
class ImpersonationsController
# controller actions go here
end
Original article on SaaS authentication.
Remember to implement the security measures before deploying to production.