Created
April 5, 2024 09:06
-
-
Save marventhieme/b86bfb37f9756e4ad94089a3909f725e to your computer and use it in GitHub Desktop.
Laravel Jetstream/Fortify/Inertia: Impersonate a user (Basic implementation)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Composer package: https://github.com/404labfr/laravel-impersonate | |
Follow the installation instructions. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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