JosephSilber / bouncer

Laravel Eloquent roles and abilities.
MIT License
3.43k stars 330 forks source link

How to allow users to own themselves? #570

Closed Synchro closed 3 years ago

Synchro commented 3 years ago

I want users to be treated as owners of their own records, so they can edit their own data but not anyone else's. How should I assign this ability? I'm currently looking at:

    Bouncer::ownedVia(
        User::class,
        function ($user, $owner) {
            return $user->id == $owner->id;
        }
    );

or is there some shortcut, as I'd imagine this is a common requirement?

JosephSilber commented 3 years ago

Simply passing in 'id' should work:

Bouncer::ownedVia(User::class, 'id');
Synchro commented 3 years ago

Thanks

huy-tran commented 3 years ago

Hi,

Where should I put this code and how to check the permission.

My code is as following: Bouncer::allow($user)->toOwn(User::class)->to(['read', 'update']);

And when checking in the authorization: Bouncer::can('update', User::class);

The authorization always return false unless I set only_owned to false within abilities table which is not ideal because I don't want the user to edit others.

Thanks in advanced.

JosephSilber commented 3 years ago

In your AppServiceProvider's boot method, add this line:

Bouncer::ownedVia(User::class, 'id');
huy-tran commented 3 years ago

Thanks @JosephSilber ,

I added that to the ServiceProvider and also adjust the authorize method in the controller to request()->user()->can('update', $user) and it works for me.

Thanks again!