我有users,app_roles,app_permissions,app_permission_app_role,app_role_user。
这些表是不言自明的,我正在创建权限,然后在角色创建上将该权限分配给新角色,然后将角色分配给用户。
我检查身份验证用户的权限如下:
@if(auth()->user()->can('some route name'))
Html...
@endif上面的条件检查用户是否可以基于指定的角色访问该内容,因为我们知道角色具有权限,并且can('some route name')参数是一个路由名称。它的工作很好.
我被困在哪里了!
表app_role_user有user_id,app_role_id,现在我添加了另一列organization_id..。(将组织视为组,其中用户可以是该组的成员,而组的所有者为该用户分配单个角色(不能分配多个角色))。因为现在用户可以在组织之间切换,用户可以在不同的组织中扮演不同的角色。
我必须为下列事项扫清道路:
@if(auth()->user()->can('some route name'))
Html...
@endif注释::
Auth::user()->current_org->id显示用户所在的组织的id
目前,我正在保存role_id、user_id、organization_id in app_role_user table。
这是我的AuthServiceProvider课,
I正在动态地向Laravel的Gate:注册权限
public function boot(GateContract $gate)
{
$this->registerPolicies();
$this->registerAllPermissions($gate);
}
protected function getPermissions() {
return $this->app->make('App\Repositories\PermissionRepository')->withRoles();
}
private function registerAllPermissions($gate) {
if (Schema::hasTable('app_permissions') and Schema::hasTable('users') and Schema::hasTable('app_roles')) {
cache()->forget('app_permissions_with_roles');
foreach ($this->getPermissions() as $permission) {
$gate->define($permission->name, function ($user) use ($permission) {
return $user->hasPermission($permission);
});
}
}
}下面是PermissionRepository类:
类PermissionRepository {受保护的$model;
public function __construct(AppPermission $model)
{
$this->model = $model;
}
public function all(){
return $this->model->all();
}
public function withRoles(){
$model = $this->model;
$permissions = cache()->remember('app_permissions_with_roles', 1*60*24, function() use($model) {
return $model->with('roles')->get();
});
return $permissions;
}}
这里是AuthServiceProvider类在registerAllPermissions中需要hasPermission(AppPermission $permission)的HasRoles 特性。
trait HasRoles {
public function assignRole($role)
{
return $this->roles()->save(
AppRole::whereName($role)->firstOrFail()
);
}
public function hasRole($role)
{
if (is_string($role)) {
return $this->roles->contains('name', $role);
}
return !! $role->intersect($this->roles)->count();
}
public function hasPermission(AppPermission $permission)
{
return $this->hasRole($permission->roles);
}
}我该怎么做,我已经尝试了很多条件,但什么也没有奏效。期待着听到你们的消息。
谢谢您的阅读,请认真阅读。
发布于 2018-08-10 13:08:06
你可以这样做
用户模型
//add organization_id as pivot field
public function roles(){
return $this->belongsToMany(AppRole::class)->withPivot('organization_id');
}
//define a function
public function orgRoles($orgId){
return $this->roles()->wherePivot('organization_id', $orgId)->get();
}现在在特性中修改hasRole函数
public function hasRole($role)
{
$orgId = Auth::user()->current_org->id;
if (is_string($role)) {
return $this->orgRoles($orgId)->contains('name', $role);
}
return !! $role->intersect($this->orgRoles($orgId))->count();
}https://stackoverflow.com/questions/51786546
复制相似问题