如何在Laravel中使用spatie权限中间件?

piok6c0g  于 7个月前  发布在  其他
关注(0)|答案(2)|浏览(78)

我正在使用Laravel 8和空间角色和权限。每个操作的权限都很好。但是如果我将删除操作权限分配给子管理员,但我直接从URL中点击创建操作,则中间件无法停止操作,因为用户没有创建权限。

public function __construct(CustomerInterface $customerInterface)
{
    $this->customerInterface = $customerInterface;
    $this->middleware(['permission:create_customer|delete_customer|edit_customer|chnage_customer_status']);
}

字符串
我在构造器中使用了上述中间件。我如何解决这个问题?

oknrviil

oknrviil1#

从我对documentation的了解来看,当您使用具有多个权限的permission中间件时,如果至少一个权限检查出来,它将允许请求继续。
你需要的是基于方法的授权,为此,Laravel使用策略,默认情况下允许你为公共方法(索引,存储,更新,显示等)编写单独的授权。
假设你让一个用户使用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方法使用它们,这里将进一步介绍。

uttx8gqw

uttx8gqw2#

在您的控制器中使用

public function __construct(MembershipService $membershipService)
{
    $this->membershipService = $membershipService;
    $this->middleware(['permission:can_view_memberships']);
}

字符串

相关问题