GithubHelp home page GithubHelp logo

stechstudio / filament-impersonate Goto Github PK

View Code? Open in Web Editor NEW
205.0 9.0 48.0 61 KB

Filament plugin that makes it easy to impersonate your users

PHP 69.52% Blade 30.48%
filament filamentphp impersonate impersonation laravel plugin

filament-impersonate's Introduction

Filament Impersonate

Latest Version on Packagist Software License

This is a plugin for Filament that makes it easy to impersonate your users.

Credit

This package uses https://github.com/404labfr/laravel-impersonate under the hood, and borrows heavily from https://github.com/KABBOUCHI/nova-impersonate.

Installation

You know the drill:

composer require stechstudio/filament-impersonate

Quickstart

1. Add table action

First open the resource where you want the impersonate action to appear. This is generally going to be your UserResource class.

Go down to the table method. After defining the table columns, you want to add Impersonate as a new action for the table via actions method. Your class should look like this:

namespace App\Filament\Resources;

use Filament\Resources\Resource;
use STS\FilamentImpersonate\Tables\Actions\Impersonate;

class UserResource extends Resource {
    public static function table(Table $table)
    {
        return $table
            ->columns([
                // ...
            ])
            ->actions([
                Impersonate::make(), // <--- 
            ]);
    }

You can also define a guard and redirectTo for the action:

Impersonate::make('impersonate')
    ->guard('another-guard')
    ->redirectTo(route('some.other.route'));

2. Add the page action

Now open the page where you would want the button to appear, this will commonly be EditUser;

Go to the getActions method and add the Impersonate page action here.

<?php
namespace App\Filament\Resources\UserResource\Pages;

use App\Filament\Resources\UserResource;
use Filament\Resources\Pages\EditRecord;
use STS\FilamentImpersonate\Pages\Actions\Impersonate;

class EditUser extends EditRecord
{
    protected static string $resource = UserResource::class;

    protected function getActions(): array
    {
        return [
            Impersonate::make()->record($this->getRecord()) // <--
        ];
    }
}

Note: you must pass the record in as seen in this example!

3. Add the banner to your blade layout

The only other step is to display a notice in your app whenever you are impersonating another user. Open up your master layout file and add <x-impersonate::banner/> before the closing </body> tag.

4. Profit!

That's it. You should now see an action icon next to each user in your Filament UserResource list:

CleanShot 2022-01-03 at 14 10 36@2x

When you click on the impersonate icon you will be logged in as that user, and redirected to your main app. You will see the impersonation banner at the top of the page, with a button to leave and return to Filament:

banner

Configuration

All configuration can be managed with ENV variables, no need to publish and edit the config directly. Just check out the config file.

Authorization

By default, only Filament admins can impersonate other users. You can control this by adding a canImpersonate method to your FilamentUser class:

class User implements FilamentUser {
    
    public function canImpersonate()
    {
        return true;
    }
    
}

You can also control which targets can be impersonated. Just add a canBeImpersonated method to the user class with whatever logic you need:

class User {

    public function canBeImpersonated()
    {
        // Let's prevent impersonating other users at our own company
        return !Str::endsWith($this->email, '@mycorp.com');
    }
    
}

Customizing the banner

The blade component has a few options you can customize.

Style

The banner is dark by default, you can set this to light, or auto.

<x-impersonate::banner style='light'/>

Display name

The banner will show the name of the impersonated user, assuming there is a name attribute. You can customize this if needed:

<x-impersonate::banner :display='auth()->user()->email'/>

filament-impersonate's People

Contributors

arjendejong12 avatar bogardo avatar charathan avatar cntabana avatar corean avatar danharrin avatar eliaszobody avatar gergo85 avatar iantasker avatar intrepidws avatar jamesdb avatar josefbehr avatar jszobody avatar juliomotol avatar lamberttraccard avatar lloricode avatar matthans0n avatar mohamedsabil83 avatar nestecha avatar oddvalue avatar pxlrbt avatar rapkis avatar ruswan avatar rvzug avatar v13axel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

filament-impersonate's Issues

localize

how to share localization files?

Localize Banner Strings.

can we customize the banner to text?
to support othe languages.
like in arabic it should be

{
"leave": "انهاء",
"Impersonating user": "انتحال شخصية المستخدم",
}

BTW: not very sure of the Arabic translations, but you got the point right ?

image

image

Always impersonating myself

In the last couple of days I noticed that when I go to impersonate any user, it "impersonates" the user I'm signed in with. Then when I "Leave" it 500 errors and I'm stuck until logging out. This plugin was working 100% perfectly until this so I'm sure I probably messed something up.

Any insight into how I should troubleshoot this issue would be greatly appreciated.

Thanks in advance.

Table Impersonate does not work with widgets

Hello,

If you have a table in which there are widgets that interact with the table(InteractsWithPageTable ) when executing the impersonate action another widget event is sent, which causes that the user is not redirected correctly.

Do you know any way to stop this from happening?

Best regards

Dark/Light mode

Hi,

Many thanks for this package. It would be great if the banner style automatically switches when filament dark mode is enabled and toggled.

Trapped in exception when impersonating soft-deleted user

I attempted to impersonate a soft-deleted user, which ends up trapping me in the following exception:

Filament\FilamentManager::getUserName(): Argument #1 ($user) must be of type Illuminate\Database\Eloquent\Model|Illuminate\Contracts\Auth\Authenticatable, null given

in reference to

<x-filament-impersonate::banner/>

I understand why this is probably happening; the intended $user is not being hydrated ->withTrashed() applied. Where exactly do I go to customize the banner, given that in the current version, it is being injected via a render hook? i.e., I did not place x-impersonate::banner into my master layout.

Temporary solution to break out of the exception was to set FILAMENT_IMPERSONATE_BANNER_RENDER_HOOK="" in .env so that I could log back in.

Banner hidden by my navbar

I have a navbar on the page that is fixed to the top. When impersonating someone, the impersonate::banner is also fixed to the top and behind the navbar. How can I make it appear below my navbar?

I tried assigning a style of top: 60px;, but that didn't work.

Thanks!

Error 403 Forbidden when clicked from table actions

Hi,

When i click Impersonate from table actions I get
Error 403 Forbidden I assume because the url stays the same mysite.test/admin/users
When I click Impersonate from Edit view everything works normally

Laravel: 11.10.0
PHP 8.2.19
Filament: v3.2.86

Thanks for your help and support

use STS\FilamentImpersonate\Tables\Actions\Impersonate;

class UserResource extends Resource

            ->actions([
                Impersonate::make(),
                EditAction::make(),
                ActionGroup::make([
                    ViewAction::make(),
                    EditAction::make(),
                    DeleteAction::make(),
                    Impersonate::make(),
                ]),
            ])

config file

<?php
return [
    // This is the guard used when logging in as the impersonated user.
    'guard' => env('FILAMENT_IMPERSONATE_GUARD', 'web'),
    
    // After impersonating this is where we'll redirect you to.
    'redirect_to' => env('FILAMENT_IMPERSONATE_REDIRECT', '/admin'),

    // We wire up a route for the "leave" button. You can change the middleware stack here if needed.
    'leave_middleware' => env('FILAMENT_IMPERSONATE_LEAVE_MIDDLEWARE', 'web'),

    'banner' => [
        // Available hooks: https://filamentphp.com/docs/3.x/support/render-hooks#available-render-hooks
        'render_hook' => env('FILAMENT_IMPERSONATE_BANNER_RENDER_HOOK', 'panels::body.start'),
    
        // Currently supports 'dark', 'light' and 'auto'.
        'style' => env('FILAMENT_IMPERSONATE_BANNER_STYLE', 'dark'),

        // Turn this off if you want `absolute` positioning, so the banner scrolls out of view
        'fixed' => env('FILAMENT_IMPERSONATE_BANNER_FIXED', true),

        // Currently supports 'top' and 'bottom'.
        'position' => env('FILAMENT_IMPERSONATE_BANNER_POSITION', 'top'),

        'styles' => [
            'light' => [
                'text' => '#1f2937',
                'background' => '#f3f4f6',
                'border' => '#e8eaec',
            ],
            'dark' => [
                'text' => '#f3f4f6',
                'background' => '#1f2937',
                'border' => '#374151',
            ],
        ]
    ],
];

Cause gap on Filament Sidebar

https://github.com/stechstudio/filament-impersonate/blob/ee92ce42de52561aaf6731390b92846329f58b13/resources/views/components/banner.blade.php#L37C4-L39

    div.fi-layout > aside.fi-sidebar {
        padding-{{ $position }}: var(--impersonate-banner-height);
    }

This line of code cause an issues with the filament sidebar, it create a gap between the sidebar and the impersonate banner.

I'm using the default setup/configuration of the plugin.

image


Disabling the Css it fixed the issue or if the position setting is top then the css will not be applied.

image
image

Trouble on impersonate from resources other than UserResource

I have a resource named InstructorResource. The Instructor model has a relational user method which belongs to User model.

I am trying to impersonate from InstructorResource by:

return $table
       ->actions([
                Impersonate::make()
                    ->redirectTo('/instructor'),

                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ]),

From the UserResource class, it is working perfectly though. Is it possible to impersonate from InstructResource?

error filamentManager::getCurrentPanel()

Get this error message when I try to impersonate a user.

Call to undefined method Filament\FilamentManager::getCurrentPanel() - Using jetstream. Livewire 2 - any idea?

Impersonate stopped working after Laravel update?

Impersonate stopped working after I updated Laravel. I was on Laravel 9.3.1 and it worked and after updating to 9.6.0 I just get logged out when I click on the impersonate button. Any ideas why? Impersonate, Filament and Jetstream are all on latest versions.

I found two things that seems to "fix" this. One is removing this line from App\Http\Kernel.php ... \Laravel\Jetstream\Http\Middleware\AuthenticateSession::class, and the other is changing Route::middleware(['auth:sanctum', 'verified']) to Route::middleware(['auth:web', 'verified']) in my routes file. Does anyone know the implications of doing any of those options?

Thank you!

It does not work with Multi-Tenant app

I am trying to add impersonate to multi-tenant app. when i hit impersonate action it throws 403 error.

FILAMENT_IMPERSONATE_REDIRECT=/console

Also tried FILAMENT_IMPERSONATE_REDIRECT=/console/1 to see if it cannot find the tenant or something but no luck.

Tried to pass a custom url to redirectTo() method and also tried to set tenant before redirecting but still does not work.

Am i missing something that should be added to make it work on multi-tenant?

Problem to impersonate with admin guard

image

I have two guards, admin and the default web. When I'm trying to impersonate an admin as a default user, I'm getting this issue.

What I'm doing wrong? If you need more information, please, let me know, and I'll share you what you need.

Thanks in advance!

Support for page action

Right now this is only available as a table action. Would be nice to be available as a page action as well, so it could be added to a View User page, for example.

Error on impersionate

Hey guys.

I have the following error when clicking the button to impersonate

Call to undefined method Filament\FilamentManager::getCurrentPanel()

Has anyone ever get this problem?

Captura de Tela 2023-10-05 às 07 27 14

Crashing when leaving impersonate

Hello, I'm a new Filament user so please excuse me if this is actually entirely my fault!

I've followed the steps to install the package and it works great, except that when I click on the "Leave" button on the banner, the app crashes with the following error.

Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, Illuminate\Routing\Redirector given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Http/Response.php on line 72
I tried setting a different redirect with the backTo() method, and through the .env file but neither worked.

Any idea why this might be happening?

Thanks!

Laravel 9 support?

Is it possible to add Laravel 9 support?

lab404/laravel-impersonate needs to be bumped up?

Thank you!

Undefined type 'App\Models\IsFilamentUser'.

In the doc it says use IsFilamentUser, but I get the message Undefined type 'App\Models\IsFilamentUser'. and it can't find anything to import. It seems to work without IsFilamentUser, but am I doing anything wrong or is the example wrong?

class User implements FilamentUser {
    use IsFilamentUser;
    
    public function canImpersonate()
    {
        return true;
    }
}

Enable to show banner

I have an issue to display the banner . I have investigated the code. I found that the issue lies in the following file:

https://github.com/stechstudio/filament-impersonate/blob/master/src/FilamentImpersonateServiceProvider.php#L37

In the original code snippet, the Filament::registerRenderHook method is used as follows:

Filament::registerRenderHook(
            'body.start',
            static fn (): string => Blade::render("<x-filament-impersonate::banner/>")
);

To resolve the issue, you can change it to the following code:

FilamentView::registerRenderHook(
            'panels::body.start',
            static fn (): string => Blade::render("<x-filament-impersonate::banner/>")
);

If you're okay with it, I can create a pull request to implement the changes.

Let me know what you think.

By the way, thank you for your plugin

Error on redirect FilamentManager::getUserName()

When redirect I'm getting this error:

Filament\FilamentManager::getUserName(): Argument #1 ($user) must be of type Illuminate\Database\Eloquent\Model|Illuminate\Contracts\Auth\Authenticatable, null given, called in /Users/daniel/Desktop/Proyectos/tickify/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 353

<x-filament-impersonate::banner/>

Multi Guard issue.

using this package with two guards "web" (those my website users) and "admins" (filament users)
and added this package to both.
the problem is when impersonating "web", it works well.
but when trying to impersonate "admins" guard, it just picks the same id in guard "web"

lost? me too 😂.

so in admins table

  • id (1) admin1
  • id (2) admin2

and in users table

  • id (1) user1
  • id (2) user2

when i click impersonate on admin2, it impersonate user2 instead.

auth.php

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'clients',
        ],

        'admins' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
    ],

Formatting of Action in a group doesn't match other Actions

When adding the impersonate Action to a Group like so:

            ->actions([
                ActionGroup::make([
                    ViewAction::make(),
                    EditAction::make(),
                    DeleteAction::make(),
                    Impersonate::make()->redirectTo('/admin'),
                ]),
            ]);

the styling isn't the same, nor does the label appear:
image

image

Is this caused by my incorrect usage of the plugin or is it a bug?

Not working when using laravel octane

It seems that this plugin isn't working properly with Laravel Octane (https://laravel.com/docs/10.x/octane).

I have an existing project where I use your plugin since you released it. Now we switched to laravel Octane (with roadrunner) on Production, and a user still can impersonate, but the top bar to end the Impersonate isn't displayed.

I can reproduce this on local system as well. I login+impersonate:

  • Using my local Apache with php-fpm or php artisan serve everything works as expected.
  • Using php artisan octane:start every thing works, except I cant see the impersonate bar.

Any ideas? Does this package use any static class properties or something? See https://laravel.com/docs/10.x/octane#dependency-injection-and-octane

Btw: Thanks for your great package!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.