Skip to content

Instantly share code, notes, and snippets.

@marventhieme
Created April 5, 2024 09:06
Show Gist options
  • Save marventhieme/b86bfb37f9756e4ad94089a3909f725e to your computer and use it in GitHub Desktop.
Save marventhieme/b86bfb37f9756e4ad94089a3909f725e to your computer and use it in GitHub Desktop.
Laravel Jetstream/Fortify/Inertia: Impersonate a user (Basic implementation)
public function boot(): void
{
// Build out the impersonation event listeners - Otherwise we get a redirect to login if not setting the password_hash_sanctum when using sanctum.
Event::listen(function (TakeImpersonation $event) {
session()->put([
'password_hash_sanctum' => $event->impersonated->getAuthPassword(),
]);
});
Event::listen(function (LeaveImpersonation $event) {
session()->remove('password_hash_web');
session()->put([
'password_hash_sanctum' => $event->impersonator->getAuthPassword(),
]);
Auth::setUser($event->impersonator);
});
}
Composer package: https://github.com/404labfr/laravel-impersonate
Follow the installation instructions.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class ImpersonateController extends Controller
{
public function startImpersonating(Request $request)
{
if(! auth()->user()?->isAdmin()){
abort(403);
}
$user = User::findOrFail($request->input('user_id'));
auth()->user()->impersonate($user);
return to_route('dashboard');
}
public function stopImpersonating(Request $request)
{
auth()->user()->leaveImpersonation();
return to_route('dashboard');
}
}
Route::post('start-impersonating', [ImpersonateController::class, 'startImpersonating'])->name('impersonating.start');
Route::post('stop-impersonating', [ImpersonateController::class, 'stopImpersonating'])->name('impersonating.stop');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment