在我的应用程序中,我使用默认的Laravel ACL来定义用户的能力,随后与角色和权限相关联 .
我设置了hasMany和belongsTo关系,其中User属于Company模型,Company有很多Users . 我想定义具有不同能力的公司的“类型”,与用户能力分开 . 例如,公司可能是一个“建筑师”公司,其能力不同于“承包商”公司,而每个公司都有一个角色为“公司管理员”的用户,可以添加或删除他们公司的用户,以及一堆“常规”用户 .
现在我已经完成了用户可以拥有角色的部分,但我对如何实施公司"type or role"感到有点迷茫 . 我在想我必须创建自己的 AuthServiceProvider
,将其他名称命名并在laravel服务提供商中注册,以及我自己的Gate实现注入公司模型而不是用户?
现在我在我的AuthServiceProvider中定义我的用户能力,并使用 Gate
Facade进行检查,例如:
在AuthServiceProvider中注册能力 .
//AuthServiceProvider
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void
*/
public function boot(GateContract $gate)
{
parent::registerPolicies($gate);
foreach ($this->getPermissions() as $permission) {
$gate->define($permission->name, function ($user) use ($permission) {
return $user->hasPermission($permission);
});
}
}
然后检查UserController上的用户能力 .
//UserController
/**
* Edit the user's email.
*
* @param User $user
*/
public function edit(User $user)
{
if(Gate::allows('edit', $user){
$user->email = $this->request->input('email');
$user->save();
}
}
我希望能够使用公司模型进行同样的检查,即:
// Check if the Company that the user belongs to is allowed to create posts
CompanyGate::allows('create-post');
1 回答
目前在您的
User
模型上,您似乎已经定义了hasPermission
函数 .您可以在
Company
模型上创建一个类似的方法来检查给定公司的角色和权限 .如果您想使用
Gate
,您仍然需要通过经过身份验证的用户检查权限,它始终会在经过身份验证的用户的上下文中验证权限 - 但是当用户属于公司时,您可以跳转到公司的权限 .类似于以下内容: