404labfr / laravel-impersonate

Laravel Impersonate is a plugin that allows you to authenticate as your users.

Home Page:https://marceau.casals.fr

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Impersonate only roles/permissions without actually impersonating a user

Astalyos opened this issue · comments

Hi, I'm actually working on a tool to be able to impersonate a user (which is totally fine until here), and impersonating a role/permission (I will call that roleplay)

I'm using Spatie/laravel-permission.

I'm looking for a way to impersonate a role without changing the logged user
For example :
roles : admin, manager, superadmin
I would like to stay logged as "Me" but temporally change my role

Does anyone have an idea of how I could do this ?

You are best of having test users for that. But if you insist… you would just implement what Laravel-impersonate does but instead of changing the user you change the users roles.

@Astalyos One way to do that might be to leverage Laravel's Gate::after() functionality. Basically, it fires after all abilities checks have been done, and then checks for additional changes that are needed. A classic use-case for this is to prevent even a super-admin from editing something that "nobody" should change, or to protect a member's private data even from Admins.

In theory you could hook into that stage and when it checks for a certain ability, your custom code will check whether the "new" role should be able to do that, and grant it, and check whether your "old"/existing/usual role should be able to do it, and if not then deny it ... basically simulating the other role. Your "trigger" for it could be a simple new session variable that tracks what role/s you're suspending and which role/s you're granting for this temporary time, and probably set an expiration with it too.

Laravel Daily posted a video which partially touches on this concept. Again, you'd want to store something in the session about the user's current state.
And if your app is built on authorizing 'abilities' related to 'permissions' (instead of always only checking whether they have a certain 'role'), like I said in my post above you'll need to track what permissions you're wanting to "keep" vs "add" to the user when they've switched roles, kinda in the way I described above.

https://www.youtube.com/watch?v=U2CZ3El5-DE

Not sure if it's the right way but, I think I've found a easier way
It has nothing to do anymore with the impersonate package but it does work

I'm storing the roles of the user in the user Db, then switch roles, and when I want to come back clear the field in the db and reattribute the right ones to the user

I'll get a look at what you sent !
Thank you for your help! Really appreciate
@drbyte @tonypartridger