在我的应用程序中,我使用默认的Laravel ACL来定义用户的能力,随后与角色和权限相关联。
我建立了hasMany和belongsTo关系,其中一个用户属于一个公司模型,一个公司有很多用户。我想定义具有不同能力的公司的"类型",与用户能力分开。例如,一家公司可能是一家"架构师"公司,其能力与"承包商"公司不同,而每家公司都有一个"公司管理员"角色的用户,可以从公司中添加或删除用户,以及一群"常规"用户。
现在,我正在处理用户可以扮演角色的部分,但我有点不知道如何实现公司的"类型或角色"。我在想,我必须创建我自己的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');
当前在User
模型上,您似乎已经定义了hasPermission
函数。
您只需在Company
模型上创建一个类似的方法,即可检查给定公司的角色和权限。
如果你想使用Gate
,你仍然需要通过经过身份验证的用户检查权限,它总是会在经过身份验证用户的上下文中验证权限,但由于用户属于一家公司,你可以跳到该公司的权限。
类似于以下内容:
$gate->define('create-post', function ($user) {
return $user->company->hasPermission('create-post');
});