How to impersonate a user using Laravel Framework
In the real world, impersonation might suggest identity theft or a criminal act. However, within the realm of QA (Quality Assurance) and application testing, it serves as a means to avoid repetitive logins into various user accounts for testing features or offering customer support.
This article will delve into incorporating the impersonation feature into your application, a valuable tool for administrators seeking to manage other users’ behaviors.
To begin, let’s acquire code samples enabling user switching based on their user model ID. Installing a Composer package will aid in managing sessions effectively.
composer require lab404/laravel-impersonate
Register the provider in the config/app.php
Lab404\Impersonate\ImpersonateServiceProvider::class,
$userId = $request->user_id;
$user = $this->userRepository->find($userId);
if ($user === null) {
return redirect()->back()->withInput();
}
$adminUser = auth()->user;
$session = $request->session();
if ($session->get('isAdmin') === null && $session->get('adminUserId') === null
) {
$session->put('isAdmin', true);
$session->put('adminUserId', $adminUser->id);
}
$manager = app('impersonate');
$manager->findUserById($userId);
$manager->isImpersonating();
// Leave current impersonation
$manager->leave();
// Impersonate an user. Pass the original user and the user you want to impersonate
$manager->take($adminUser, $user);
$request->setUserResolver(fn () => $user);
Once the package is installed, you’ll need to develop a function responsible for capturing the current user and storing it within a session. This facilitates the seamless transition back to the original user account after completing tasks in the impersonated account.
The package provides some useful APIs to switch the session between the impersonator and the user being impersonated.
For example;
$manager->leave();
The purpose of the leave() function is to remove the current user from the ongoing session, thereby altering the session behavior.
$manager->take($adminUser, $user);
This action will substitute the admin user’s session with the user account you’re currently impersonating, effectively swapping their session context.
$request->setUserResolver(fn () => $user);
The function above establishes the request binding of the current user to every request made within the application.
In the latter section of the code, the impersonator is reverting to their original account. This signifies that the user ID stored in the session will be utilized to regain their authentic access to the application.
$userId = $request->session()->get('adminUserId');
if (empty($userId) === false) {
$manager = app('impersonate');
$user = $manager->findUserById($userId);
$manager->isImpersonating();
// Leave current impersonation
$manager->leave();
$manager->take(auth()->user, $user);
$request->setUserResolver(fn () => $user);
$request->session()->forget(['adminUserId', 'isAdmin']);
}
The code above bears resemblance to the initial section, albeit this time, the session needs to be cleared to remove any reference to the stored impersonator identity.
Thank you for taking the time to go through this article. I hope it proves beneficial to you. Please share any feedback you have here, and I’ll do my best to respond to it.