在我的应用程序中,我使用默认的Laravel来定义用户的能力,并随后与角色和权限相关联。
我建立了一个hasMany和一个belongsTo关系,其中一个用户属于一个公司模型,一个公司有很多用户。我想定义的“类型”的公司,有不同的能力,不同的用户能力。例如,一家公司可能是一家能力不同于“承包商”公司的“建筑师”公司,而每一家公司都有一个用户,其角色是“公司管理员”,可以从公司中添加或删除用户,以及一群“常规”用户。
现在我已经做了一个用户可以有一个角色的部分,但我有点不知道如何实现公司的“类型或角色”。我在想,我必须创建我自己的AuthServiceProvider
,命名它,并在laravel服务提供商中注册它,以及我自己实现的门,注入了公司模型,而不是用户?
现在,我正在AuthServiceProvider中定义我的用户能力,并使用Gate
外观进行检查,例如:
在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');
发布于 2016-05-13 16:07:25
目前,在您的User
模型中,您似乎已经定义了一个hasPermission
函数。
您可以简单地在Company
模型上创建一个类似的方法,该方法检查给定公司的角色和权限。
如果您想使用Gate
,您仍然需要通过经过身份验证的用户检查权限,它总是要在经过身份验证的用户的上下文中验证权限--但是由于用户属于公司,所以您可以跳到公司的权限。
类似于以下几点:
$gate->define('create-post', function ($user) {
return $user->company->hasPermission('create-post');
});
https://stackoverflow.com/questions/37213068
复制相似问题