$tenant->getTenantKey(), 'user_id' => $userId, 'redirect_url' => $redirectUrl, 'auth_guard' => $authGuard, 'remember' => $remember, ]); }); } /** Impersonate a user and get an HTTP redirect response. */ public static function makeResponse(#[\SensitiveParameter] string|Model $token, ?int $ttl = null): RedirectResponse { /** * The model does NOT have to extend ImpersonationToken, but usually it WILL be a child * of ImpersonationToken and this makes it clear to phpstan that the model has a redirect_url property. * * @var ImpersonationToken $token */ $token = $token instanceof Model ? $token : static::modelClass()::findOrFail($token); $ttl ??= static::$ttl; $tokenExpired = $token->created_at->diffInSeconds(now()) > $ttl; abort_if($tokenExpired, 403); $tokenTenantId = (string) $token->getAttribute(Tenancy::tenantKeyColumn()); $currentTenantId = (string) tenant()->getTenantKey(); abort_unless($tokenTenantId === $currentTenantId, 403); Auth::guard($token->auth_guard)->loginUsingId($token->user_id, $token->remember); $token->delete(); session()->put('tenancy_impersonating', true); return redirect($token->redirect_url); } /** @return class-string */ public static function modelClass(): string { return config('tenancy.models.impersonation_token'); } public static function isImpersonating(): bool { return session()->has('tenancy_impersonating'); } /** * Logout from the current domain and forget impersonation session. */ public static function stopImpersonating(): void { auth()->logout(); session()->forget('tenancy_impersonating'); } }