mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-12 15:34:03 +00:00
User impersonation
This commit is contained in:
parent
52476d6298
commit
10a5b80d44
9 changed files with 432 additions and 2 deletions
54
src/Features/UserImpersonation.php
Normal file
54
src/Features/UserImpersonation.php
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
<?php
|
||||
|
||||
namespace Stancl\Tenancy\Features;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Stancl\Tenancy\Contracts\Feature;
|
||||
use Stancl\Tenancy\Database\Models\ImpersonationToken;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Tenancy;
|
||||
|
||||
class UserImpersonation implements Feature
|
||||
{
|
||||
public static $ttl = 60; // seconds
|
||||
|
||||
public function bootstrap(Tenancy $tenancy): void
|
||||
{
|
||||
$tenancy->macro('impersonate', function (Tenant $tenant, string $userId, string $redirectUrl, string $authGuard = null): ImpersonationToken
|
||||
{
|
||||
return ImpersonationToken::create([
|
||||
'tenant_id' => $tenant->getTenantKey(),
|
||||
'user_id' => $userId,
|
||||
'redirect_url' => $redirectUrl,
|
||||
'auth_guard' => $authGuard,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Impersonate a user and get an HTTP redirect response.
|
||||
*
|
||||
* @param string|ImpersonationToken $token
|
||||
* @return RedirectResponse
|
||||
*/
|
||||
public static function makeResponse($token): RedirectResponse
|
||||
{
|
||||
$token = $token instanceof ImpersonationToken ? $token : ImpersonationToken::findOrFail($token);
|
||||
|
||||
if (((string) $token->tenant_id) !== ((string) tenant('id'))) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
if ($token->created_at->diffInSeconds(Carbon::now()) > static::$ttl) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
Auth::guard($token->auth_guard)->loginUsingId($token->user_id);
|
||||
|
||||
$token->delete();
|
||||
|
||||
return redirect($token->redirect_url);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue