User impersonation allows administrators to temporarily log in as another user without knowing their password. This is particularly useful for:
Providing customer support
Testing user-specific issues
Debugging permission problems
Quality assurance testing
User impersonation is a powerful feature that should only be available to trusted administrators. It provides full access to the impersonated user’s account.
The impersonation system uses AdonisJS sessions to store the original user’s ID before switching to the target user. This allows administrators to seamlessly switch back to their own account.
The impersonation controller handles the session management and authentication:
app/users/controllers/impersonates_controller.ts
import type { HttpContext } from '@adonisjs/core/http'import { afterAuthRedirectRoute } from '#config/auth'import User from '#users/models/user'import ImpersonatePolicy from '#users/policies/impersonate_policy'export default class ImpersonatesController { async store({ session, bouncer, params, response, auth }: HttpContext) { const impersonatedUser = await User.findOrFail(params.id) // Check if the current user has permission to impersonate await bouncer.with(ImpersonatePolicy).authorize('create', impersonatedUser) // Store the original user ID in the session session.put('originalUserId', auth.user!.id) // Log in as the target user await auth.use('web').login(impersonatedUser) return response.redirect().toRoute(afterAuthRedirectRoute) }}
The starter kit includes a React dialog component for triggering impersonation:
// Example UI button<Button onClick={() => impersonateUser(user.id)} disabled={!canImpersonate}> Impersonate User</Button>
The impersonation feature is already implemented in the starter kit’s user management interface. Admins will see an “Impersonate” option in the user list.