Projectslaravel-impersonation

Laravel Impersonation

Package

Session-based user impersonation for Laravel.

Impersonation

A simple yet flexible implementation of Impersonation Management in Laravel.

Static Analysis Tests Laravel Version PHP Version

Introduction

A simple impersonation manager that facilitates session-based impersonation of users, with support for recursive impersonation, if needed.

Installation

composer require bradietilley/laravel-impersonation

Documentation

The BradieTilley\Impersonation\ImpersonationManager singleton can be swapped out for your own.

Usage of this is fairly straight-forward, it can be depedency injected or statically called.

Usage

Check if the authorised user can impersonate

ImpersonationManager::make()->canImpersonate($user);

Begin impersonating a given user

ImpersonationManager::make()->impersonate($user);

Check if the authorised user is currently impersonating

ImpersonationManager::make()->isImpersonating();

Stop impersonating

ImpersonationManager::make()->stopImpersonating();

Authorising who can impersonate

In your service provider you should specify a callback to control who can impersonate.

ImpersonationManager::configure(
    authorize: function (User $admin, User $user) {
        return $admin->isAdmin() && ! $user->isAdmin();
    },
);

This callback will be invoked as part of the ImpersonationManager::make()->canImpersonate($user); check, and will ultimately serve as a simple gate check for who can impersonate who.

Author