Silvanite / novatoolpermissions

Laravel Nova Permissions Tool (User, Roles and Permissions / Access Control (ACL))
MIT License
101 stars 33 forks source link

Policy not working #41

Closed patricktsg closed 5 years ago

patricktsg commented 5 years ago

I've created a ProductPolicy but it's not working - I assigned a test user to it and logged in as them and can still see Products (resource) despite not having given the user the role.

patricktsg commented 5 years ago

The default User and roles one's work fine but not my custom one:

ProductPolicy.php `<?php

namespace App\Policies;

use App\User; use App\Product; use Illuminate\Support\Facades\Gate; use Illuminate\Auth\Access\HandlesAuthorization;

class ProductPolicy { use HandlesAuthorization;

// /**
//  * Create a new policy instance.
//  *
//  * @return void
//  */
// public function __construct()
// {
//     //
// }

public function viewAny($user)
{
    return Gate::any(['viewProducts', 'manageProducts'], $user);
}

public function view($user, $product)
{
    return Gate::any(['viewProducts', 'manageProducts'], $user, $product);
}

public function create($user)
{
    return $user->can('manageProducts');
}

public function update($user, $product)
{
    return $user->can('manageProducts', $product);
}

public function delete($user, $product)
{
    return $user->can('manageProducts', $product);
}

public function restore($user, $product)
{
    return $user->can('manageProducts', $product);
}

public function forceDelete($user, $product)
{
    return $user->can('manageProducts', $product);
}

} `

AuthServiceProvider.php ` namespace App\Providers;

use Illuminate\Support\Facades\Gate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Silvanite\Brandenburg\Traits\ValidatesPermissions;

class AuthServiceProvider extends ServiceProvider { use ValidatesPermissions;

protected $policies = [
    \App\Product::class => \App\Policies\ProductPolicy::class,
];

public function boot()
{
    collect([
        'viewProducts',
        'manageProducts',
    ])->each(function ($permission) {
        Gate::define($permission, function ($user) use ($permission) {
            if ($this->nobodyHasAccess($permission)) {
                return true;
            }

            return $user->hasRoleWithPermission($permission);
        });
    });

    $this->registerPolicies();
}

}`

m2de commented 5 years ago

Hi @patricktsg . That all looks good at first glance. You can either remove the nobodyHasAccess call from the gate definition or you need to ensure that at least 1 user is assigned to a Role which has this permission. Just assigning the permission to a Role (without attaching the Role to a User) will still fire the nobodyHasAccess. Let me know if that works. Cheers.

patricktsg commented 5 years ago

@m2de Awesome that worked, also I think I kept running a migrate:fresh which was wiping my roles out! Doh!