问题描述
我正在使用 Laravel 8 和 Spatie 角色和权限。每个动作的权限都工作正常。但是,如果我为子管理员分配了删除操作权限,但我直接从 URL 中点击了 创建操作,因为用户没有创建权限,所以中间件无法停止操作。
public function __construct(CustomerInterface $customerInterface)
{
$this->customerInterface = $customerInterface;
$this->middleware(['permission:create_customer|delete_customer|edit_customer|chnage_customer_status']);
}
解决方法
从我从 documentation 中可以看出,当您使用具有多个权限的 permission
中间件时,如果至少一个权限检出,它将让请求继续进行.
您需要的是基于方法的授权,为此,Laravel 使用 policies,默认情况下,您可以为常用方法编写单独的授权。 (索引、存储、更新、显示等)
假设您只允许用户在拥有 store
权限时使用 create_customer
方法,您的策略将如下所示:
/**
* Determine whether the user can create models.
*
* @param User $user
* @return mixed
*/
public function create(User $user)
{
return $user->can('create_customer');
}
然后在您的控制器中放置 authorizeResource
函数,该函数将默认策略方法与您的默认资源控制器方法相关联:
public function __construct(CustomerInterface $customerInterface)
{
$this->customerInterface = $customerInterface;
$this->authorizeResource(Customer::class); // assuming your model name is Customer
}
或者,您可以编写自己的自定义策略方法并通过 $this->authorize
方法使用它们,该方法在 here 中有进一步说明。