【发布时间】:2019-01-18 01:43:12
【问题描述】:
我有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 课程,
我正在向 Laravel's 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;
}
}
这里是 HasRoles trait 具有 hasPermission(AppPermission $permission) 因为 AuthServiceProvider 类在 registerAllPermissions 中需要它。
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);
}
}
我该怎么办,我尝试了很多条件,但没有任何效果。 期待收到你们的来信。
感谢阅读,请认真关注。
【问题讨论】:
标签: php laravel permissions authorization roles