Laravel Impersonate

repository·master·Indexed 25 days ago

https://github.com/404labfr/laravel-impersonate

A Laravel package that allows administrators or authorized users to authenticate as other users. It features a trait-based implementation, built-in routing via a route macro, Blade directives for UI control, and the ImpersonateManager for manual session control. The package includes the impersonate.protect middleware to block impersonators from sensitive routes and dispatches TakeImpersonation and LeaveImpersonation events for auditing and logging.

Tokens
3.3K
Snippets
8
Records
23
Agent score
80%

What's inside laravel-impersonate

  1. Listen to impersonation events

    master

    The package dispatches two events that you can listen to:

    • TakeImpersonation: Fired when an impersonation session begins.
    • LeaveImpersonation: Fired when an impersonation session ends.

    Both events provide access to the following properties:

    • $event->impersonator: The User model instance of the original user.
    • $event->impersonated: The User model instance of the user being impersonated.
  2. Install Laravel Impersonate

    master

    To install the package, require it via Composer and register the service provider in your Laravel application.

    1. Install via Composer:
    composer require lab404/laravel-impersonate
    1. Register the service provider in config/app.php:
    'providers' => [
        // ...
        Lab404\Impersonate\ImpersonateServiceProvider::class,
    ],
    1. Add the Lab404\Impersonate\Models\Impersonate trait to your User model to enable impersonation capabilities.
  3. Use the built-in impersonation controller and routes

    master

    The package provides a route macro to set up built-in routes for impersonating and leaving impersonation. You must call this macro within your web middleware group.

    Registering the routes

    In your routes/web.php or RouteServiceProvider:

    Route::impersonate();

    Generating URLs

    • Impersonate a user: route('impersonate', $id)
      • For multi-guard setups: route('impersonate', ['id' => $id, 'guardName' => 'admin'])
    • Leave impersonation: route('impersonate.leave')
  4. Configure impersonation settings

    master

    Publish the configuration file using:

    php artisan vendor:publish --tag=impersonate

    Configuration Keys:

    • session_key: The session key used to store the original user ID (default: 'impersonated_by').
    • take_redirect_to: Where to redirect after taking an impersonation (used by the built-in controller). Can be a URI, the keyword back, or a route name.
    • leave_redirect_to: Where to redirect after leaving an impersonation (used by the built-in controller). Can be a URI, the keyword back, or a route name.
  5. Use the ImpersonateManager for manual control

    master

    You can interact with the ImpersonateManager directly via the app('impersonate') helper or dependency injection to perform advanced operations.

    Available Methods:

    • $manager->findUserById($id): Find a user by ID.
    • $manager->isImpersonating(): Returns true if the current session is an impersonation.
    • $manager->take($from, $to): Manually switch from one user to another.
    • $manager->leave(): Leave the current impersonation.
    • $manager->getImpersonatorId(): Retrieve the ID of the user who is performing the impersonation.
    $manager = app('impersonate');
    
    $manager->isImpersonating();
    $manager->take($from, $to);
    $manager->leave();
    $manager->getImpersonatorId();
  6. Use Blade directives for impersonation UI

    master

    The package provides three Blade directives to conditionally show UI elements based on impersonation status:

    • @canImpersonate($guard = null): Renders content if the current user is allowed to impersonate others.
    • @canBeImpersonated($user, $guard = null): Renders content if the specific $user is allowed to be impersonated.
    • @impersonating($guard = null): Renders content if the current user is currently impersonating someone else.
    @canImpersonate($guard = null)
        <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
    @endCanImpersonate
    
    @canBeImpersonated($user, $guard = null)
        <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
    @endCanBeImpersonated
    
    @impersonating($guard = null)
        <a href="{{ route('impersonate.leave') }}">Leave impersonation</a>
    @endImpersonating
  7. Impersonate and leave impersonation via Auth user

    master

    Once the Impersonate trait is added to your User model, you can use the following methods on the currently authenticated user instance:

    • impersonate($other_user): Authenticate as another user.
    • leaveImpersonation(): Return to the original authenticated user.
    Auth::user()->impersonate($other_user);
    // You're now logged as the $other_user
    
    Auth::user()->leaveImpersonation();
    // You're now logged as your original user.
  8. Protect routes from impersonators

    master

    Use the impersonate.protect middleware to prevent impersonated users from accessing sensitive routes (e.g., payment settings or credit card details). If an impersonator attempts to access a protected route, they will be blocked.

    Router::get('/my-credit-card', function() {
        echo "Can't be accessed by an impersonator";
    })->middleware('impersonate.protect');
  9. Define impersonation authorization logic

    master

    By default, any user can impersonate any other user. You can restrict this by adding specific methods to your User model:

    • canImpersonate(): Controls whether the current user is allowed to start an impersonation session.
    • canBeImpersonated(): Controls whether a user is allowed to be the target of an impersonation session.
    /**
     * @return bool
     */
    public function canImpersonate()
    {
        return $this->is_admin == 1;
    }
    
    /**
     * @return bool
     */
    public function canBeImpersonated()
    {
        return $this->can_be_impersonated == 1;
    }
  10. Configure ImpersonateManager session and redirect keys

    master

    The ImpersonateManager relies on several configuration keys from config/laravel-impersonate.php to manage session state and redirection logic. You can access these via the manager's getter methods:

    MethodConfig KeyDescription
    getSessionKey()laravel-impersonate.session_keyThe key used to store the impersonator's ID in the session.
    getSessionGuard()laravel-impersonate.session_guardThe key used to store the impersonator's guard in the session.
    getSessionGuardUsing()laravel-impersonate.session_guard_usingThe key used to store the guard being used for impersonation.
    getTakeRedirectTo()laravel-impersonate.take_redirect_toThe route name or URI to redirect to after take() is called.
    getLeaveRedirectTo()laravel-impersonate.leave_redirect_toThe route name or URI to redirect to after leave() is called.