vendor and env first commit

This commit is contained in:
2025-03-28 08:52:46 +01:00
parent f8388bc81b
commit 8f26283832
10976 changed files with 1349952 additions and 2 deletions
@@ -0,0 +1,81 @@
<?php
namespace Lab404\Impersonate\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Lab404\Impersonate\Services\ImpersonateManager;
class ImpersonateController extends Controller
{
/** @var ImpersonateManager */
protected $manager;
/**
* ImpersonateController constructor.
*/
public function __construct()
{
$this->manager = app()->make(ImpersonateManager::class);
$guard = $this->manager->getDefaultSessionGuard();
$this->middleware('auth:' . $guard)->only('take');
}
/**
* @param int $id
* @param string|null $guardName
* @return RedirectResponse
* @throws \Exception
*/
public function take(Request $request, $id, $guardName = null)
{
$guardName = $guardName ?? $this->manager->getDefaultSessionGuard();
// Cannot impersonate yourself
if ($id == $request->user()->getAuthIdentifier() && ($this->manager->getCurrentAuthGuardName() == $guardName)) {
abort(403);
}
// Cannot impersonate again if you're already impersonate a user
if ($this->manager->isImpersonating()) {
abort(403);
}
if (!$request->user()->canImpersonate()) {
abort(403);
}
$userToImpersonate = $this->manager->findUserById($id, $guardName);
if ($userToImpersonate->canBeImpersonated()) {
if ($this->manager->take($request->user(), $userToImpersonate, $guardName)) {
$takeRedirect = $this->manager->getTakeRedirectTo();
if ($takeRedirect !== 'back') {
return redirect()->to($takeRedirect);
}
}
}
return redirect()->back();
}
/**
* @return RedirectResponse
*/
public function leave()
{
if (!$this->manager->isImpersonating()) {
abort(403);
}
$this->manager->leave();
$leaveRedirect = $this->manager->getLeaveRedirectTo();
if ($leaveRedirect !== 'back') {
return redirect()->to($leaveRedirect);
}
return redirect()->back();
}
}
@@ -0,0 +1,34 @@
<?php
namespace Lab404\Impersonate\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class LeaveImpersonation
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/** @var Authenticatable */
public $impersonator;
/** @var Authenticatable */
public $impersonated;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Authenticatable $impersonator, Authenticatable $impersonated)
{
$this->impersonator = $impersonator;
$this->impersonated = $impersonated;
}
}
@@ -0,0 +1,34 @@
<?php
namespace Lab404\Impersonate\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class TakeImpersonation
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/** @var Authenticatable */
public $impersonator;
/** @var Authenticatable */
public $impersonated;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Authenticatable $impersonator, Authenticatable $impersonated)
{
$this->impersonator = $impersonator;
$this->impersonated = $impersonated;
}
}
@@ -0,0 +1,13 @@
<?php
namespace Lab404\Impersonate\Exceptions;
use Throwable;
class InvalidUserProvider extends \Exception
{
public function __construct(string $guard, $message = "", $code = 0, Throwable $previous = null)
{
parent::__construct(sprintf('Invalid user provider for guard %s', $guard), $code, $previous);
}
}
@@ -0,0 +1,13 @@
<?php
namespace Lab404\Impersonate\Exceptions;
use Throwable;
class MissingUserProvider extends \Exception
{
public function __construct(string $guard, $message = "", $code = 0, Throwable $previous = null)
{
parent::__construct(sprintf('Missing user provider for guard %s', $guard), $code, $previous);
}
}
@@ -0,0 +1,38 @@
<?php
namespace Lab404\Impersonate\Guard;
use Illuminate\Auth\SessionGuard as BaseSessionGuard;
use Illuminate\Contracts\Auth\Authenticatable;
class SessionGuard extends BaseSessionGuard
{
/**
* Log a user into the application without firing the Login event.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @return void
*/
public function quietLogin(Authenticatable $user)
{
$this->updateSession($user->getAuthIdentifier());
$this->setUser($user);
}
/**
* Logout the user without updating remember_token
* and without firing the Logout event.
*
* @param void
* @return void
*/
public function quietLogout()
{
$this->clearUserDataFromStorage();
$this->user = null;
$this->loggedOut = true;
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace Lab404\Impersonate;
use Illuminate\Support\Facades\Facade;
use Lab404\Impersonate\Services\ImpersonateManager;
class Impersonate extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return ImpersonateManager::class;
}
}
@@ -0,0 +1,188 @@
<?php
namespace Lab404\Impersonate;
use Illuminate\Auth\AuthManager;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Event;
use Illuminate\View\Compilers\BladeCompiler;
use Lab404\Impersonate\Guard\SessionGuard;
use Lab404\Impersonate\Middleware\ProtectFromImpersonation;
use Lab404\Impersonate\Services\ImpersonateManager;
/**
* Class ServiceProvider
*
* @package Lab404\Impersonate
*/
class ImpersonateServiceProvider extends \Illuminate\Support\ServiceProvider
{
/** @var string $configName */
protected $configName = 'laravel-impersonate';
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfig();
$this->app->bind(ImpersonateManager::class, ImpersonateManager::class);
$this->app->singleton(ImpersonateManager::class, function ($app) {
return new ImpersonateManager($app);
});
$this->app->alias(ImpersonateManager::class, 'impersonate');
$this->registerRoutesMacro();
$this->registerBladeDirectives();
$this->registerMiddleware();
$this->registerAuthDriver();
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->publishConfig();
// We want to remove data from storage on real login and logout
Event::listen(Login::class, function ($event) {
app('impersonate')->clear();
});
Event::listen(Logout::class, function ($event) {
app('impersonate')->clear();
});
}
/**
* Register plugin blade directives.
*
* @param void
* @return void
*/
protected function registerBladeDirectives()
{
$this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
$bladeCompiler->directive('impersonating', function ($guard = null) {
return "<?php if (is_impersonating({$guard})) : ?>";
});
$bladeCompiler->directive('endImpersonating', function () {
return '<?php endif; ?>';
});
$bladeCompiler->directive('canImpersonate', function ($guard = null) {
return "<?php if (can_impersonate({$guard})) : ?>";
});
$bladeCompiler->directive('endCanImpersonate', function () {
return '<?php endif; ?>';
});
$bladeCompiler->directive('canBeImpersonated', function ($expression) {
$args = preg_split("/,(\s+)?/", $expression);
$guard = $args[1] ?? null;
return "<?php if (can_be_impersonated({$args[0]}, {$guard})) : ?>";
});
$bladeCompiler->directive('endCanBeImpersonated', function () {
return '<?php endif; ?>';
});
});
}
/**
* Register routes macro.
*
* @param void
* @return void
*/
protected function registerRoutesMacro()
{
$router = $this->app['router'];
$router->macro('impersonate', function () use ($router) {
$router->get('/impersonate/take/{id}/{guardName?}',
'\Lab404\Impersonate\Controllers\ImpersonateController@take')->name('impersonate');
$router->get('/impersonate/leave',
'\Lab404\Impersonate\Controllers\ImpersonateController@leave')->name('impersonate.leave');
});
}
/**
* @param void
* @return void
*/
protected function registerAuthDriver()
{
/** @var AuthManager $auth */
$auth = $this->app['auth'];
$auth->extend('session', function (Application $app, $name, array $config) use ($auth) {
$provider = $auth->createUserProvider($config['provider']);
$guard = new SessionGuard($name, $provider, $app['session.store']);
if (method_exists($guard, 'setCookieJar')) {
$guard->setCookieJar($app['cookie']);
}
if (method_exists($guard, 'setDispatcher')) {
$guard->setDispatcher($app['events']);
}
if (method_exists($guard, 'setRequest')) {
$guard->setRequest($app->refresh('request', $guard, 'setRequest'));
}
return $guard;
});
}
/**
* Register plugin middleware.
*
* @param void
* @return void
*/
public function registerMiddleware()
{
$this->app['router']->aliasMiddleware('impersonate.protect', ProtectFromImpersonation::class);
}
/**
* Merge config file.
*
* @param void
* @return void
*/
protected function mergeConfig()
{
$configPath = __DIR__ . '/../config/' . $this->configName . '.php';
$this->mergeConfigFrom($configPath, $this->configName);
}
/**
* Publish config file.
*
* @param void
* @return void
*/
protected function publishConfig()
{
$configPath = __DIR__ . '/../config/' . $this->configName . '.php';
$this->publishes([$configPath => config_path($this->configName . '.php')], 'impersonate');
}
}
@@ -0,0 +1,28 @@
<?php
namespace Lab404\Impersonate\Middleware;
use Closure;
use Illuminate\Support\Facades\Redirect;
use Lab404\Impersonate\Services\ImpersonateManager;
class ProtectFromImpersonation
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$impersonate_manager = app()->make(ImpersonateManager::class);
if ($impersonate_manager->isImpersonating()) {
return Redirect::back();
}
return $next($request);
}
}
@@ -0,0 +1,67 @@
<?php
namespace Lab404\Impersonate\Models;
use Illuminate\Database\Eloquent\Model;
use Lab404\Impersonate\Services\ImpersonateManager;
trait Impersonate
{
/**
* Return true or false if the user can impersonate an other user.
*
* @param void
* @return bool
*/
public function canImpersonate()
{
return true;
}
/**
* Return true or false if the user can be impersonate.
*
* @param void
* @return bool
*/
public function canBeImpersonated()
{
return true;
}
/**
* Impersonate the given user.
*
* @param Model $user
* @param string|null $guardName
* @return bool
*/
public function impersonate(Model $user, $guardName = null)
{
return app(ImpersonateManager::class)->take($this, $user, $guardName);
}
/**
* Check if the current user is impersonated.
*
* @param void
* @return bool
*/
public function isImpersonated()
{
return app(ImpersonateManager::class)->isImpersonating();
}
/**
* Leave the current impersonation.
*
* @param void
* @return bool
*/
public function leaveImpersonation()
{
if ($this->isImpersonated()) {
return app(ImpersonateManager::class)->leave();
}
}
}
@@ -0,0 +1,259 @@
<?php
namespace Lab404\Impersonate\Services;
use Exception;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Application;
use Lab404\Impersonate\Events\LeaveImpersonation;
use Lab404\Impersonate\Events\TakeImpersonation;
use Lab404\Impersonate\Exceptions\InvalidUserProvider;
use Lab404\Impersonate\Exceptions\MissingUserProvider;
class ImpersonateManager
{
const REMEMBER_PREFIX = 'remember_web';
/** @var Application $app */
private $app;
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* @param int $id
* @return \Illuminate\Contracts\Auth\Authenticatable
* @throws MissingUserProvider
* @throws InvalidUserProvider
* @throws ModelNotFoundException
*/
public function findUserById($id, $guardName = null)
{
if (empty($guardName)) {
$guardName = $this->app['config']->get('auth.default.guard', 'web');
}
$providerName = $this->app['config']->get("auth.guards.$guardName.provider");
if (empty($providerName)) {
throw new MissingUserProvider($guardName);
}
try {
/** @var UserProvider $userProvider */
$userProvider = $this->app['auth']->createUserProvider($providerName);
} catch (\InvalidArgumentException $e) {
throw new InvalidUserProvider($guardName);
}
if (!($modelInstance = $userProvider->retrieveById($id))) {
$model = $this->app['config']->get("auth.providers.$providerName.model");
throw (new ModelNotFoundException())->setModel(
$model,
$id
);
}
return $modelInstance;
}
public function isImpersonating(): bool
{
return session()->has($this->getSessionKey());
}
/**
* @return int|null
*/
public function getImpersonatorId()
{
return session($this->getSessionKey(), null);
}
/**
* @return \Illuminate\Contracts\Auth\Authenticatable
*/
public function getImpersonator()
{
$id = session($this->getSessionKey(), null);
return is_null($id) ? null : $this->findUserById($id, $this->getImpersonatorGuardName());
}
/**
* @return string|null
*/
public function getImpersonatorGuardName()
{
return session($this->getSessionGuard(), null);
}
/**
* @return string|null
*/
public function getImpersonatorGuardUsingName()
{
return session($this->getSessionGuardUsing(), null);
}
/**
* @param \Illuminate\Contracts\Auth\Authenticatable $from
* @param \Illuminate\Contracts\Auth\Authenticatable $to
* @param string|null $guardName
* @return bool
*/
public function take($from, $to, $guardName = null)
{
$this->saveAuthCookieInSession();
try {
$currentGuard = $this->getCurrentAuthGuardName();
session()->put($this->getSessionKey(), $from->getAuthIdentifier());
session()->put($this->getSessionGuard(), $currentGuard);
session()->put($this->getSessionGuardUsing(), $guardName);
$this->app['auth']->guard($currentGuard)->quietLogout();
$this->app['auth']->guard($guardName)->quietLogin($to);
} catch (\Exception $e) {
unset($e);
return false;
}
$this->app['events']->dispatch(new TakeImpersonation($from, $to));
return true;
}
public function leave(): bool
{
try {
$impersonated = $this->app['auth']->guard($this->getImpersonatorGuardUsingName())->user();
$impersonator = $this->findUserById($this->getImpersonatorId(), $this->getImpersonatorGuardName());
$this->app['auth']->guard($this->getCurrentAuthGuardName())->quietLogout();
$this->app['auth']->guard($this->getImpersonatorGuardName())->quietLogin($impersonator);
$this->extractAuthCookieFromSession();
$this->clear();
} catch (\Exception $e) {
unset($e);
return false;
}
$this->app['events']->dispatch(new LeaveImpersonation($impersonator, $impersonated));
return true;
}
public function clear()
{
session()->forget($this->getSessionKey());
session()->forget($this->getSessionGuard());
session()->forget($this->getSessionGuardUsing());
}
public function getSessionKey(): string
{
return config('laravel-impersonate.session_key');
}
public function getSessionGuard(): string
{
return config('laravel-impersonate.session_guard');
}
public function getSessionGuardUsing(): string
{
return config('laravel-impersonate.session_guard_using');
}
public function getDefaultSessionGuard(): string
{
return config('laravel-impersonate.default_impersonator_guard');
}
public function getTakeRedirectTo(): string
{
try {
$uri = route(config('laravel-impersonate.take_redirect_to'));
} catch (\InvalidArgumentException $e) {
$uri = config('laravel-impersonate.take_redirect_to');
}
return $uri;
}
public function getLeaveRedirectTo(): string
{
try {
$uri = route(config('laravel-impersonate.leave_redirect_to'));
} catch (\InvalidArgumentException $e) {
$uri = config('laravel-impersonate.leave_redirect_to');
}
return $uri;
}
/**
* @return array|null
*/
public function getCurrentAuthGuardName()
{
$guards = array_keys(config('auth.guards'));
foreach ($guards as $guard) {
if ($this->app['auth']->guard($guard)->check()) {
return $guard;
}
}
return null;
}
protected function saveAuthCookieInSession(): void
{
$cookie = $this->findByKeyInArray($this->app['request']->cookies->all(), static::REMEMBER_PREFIX);
$key = $cookie->keys()->first();
$val = $cookie->values()->first();
if (!$key || !$val) {
return;
}
session()->put(static::REMEMBER_PREFIX, [
$key,
$val,
]);
}
protected function extractAuthCookieFromSession(): void
{
if (!$session = $this->findByKeyInArray(session()->all(), static::REMEMBER_PREFIX)->first()) {
return;
}
$this->app['cookie']->queue($session[0], $session[1]);
session()->forget($session);
}
/**
* @param array $values
* @param string $search
* @return \Illuminate\Support\Collection
*/
protected function findByKeyInArray(array $values, string $search)
{
return collect($values ?? session()->all())
->filter(function ($val, $key) use ($search) {
return strpos($key, $search) !== false;
});
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
use Illuminate\Contracts\Auth\Authenticatable;
if (! function_exists('can_impersonate')) {
/**
* Check whether the current user is authorized to impersonate.
*
* @param null $guard
* @return bool
*/
function can_impersonate(string $guard = null): bool
{
$guard = $guard ?? app('impersonate')->getCurrentAuthGuardName();
return app('auth')->guard($guard)->check()
&& app('auth')->guard($guard)->user()->canImpersonate();
}
}
if (! function_exists('can_be_impersonated')) {
/**
* Check whether the specified user can be impersonated.
*
* @param Authenticatable $user
* @param string|null $guard
* @return bool
*/
function can_be_impersonated(Authenticatable $user, string $guard = null): bool
{
$guard = $guard ?? app('impersonate')->getCurrentAuthGuardName();
return app('auth')->guard($guard)->check()
&& app('auth')->guard($guard)->user()->isNot($user)
&& $user->canBeImpersonated();
}
}
if (! function_exists('is_impersonating')) {
/**
* Check whether the current user is being impersonated.
*
* @param string|null $guard
* @return bool
*/
function is_impersonating(string $guard = null): bool
{
$guard = $guard ?? app('impersonate')->getCurrentAuthGuardName();
return app('auth')->guard($guard)->check()
&& app('auth')->guard($guard)->user()->isImpersonated();
}
}