[英]Problems with Laravel Policies Authorization
I really do not understand what happend. 我真的不明白发生了什么。 Here is my setup and code
这是我的设置和代码
In the UserGroupPolicy class 在UserGroupPolicy类中
//Here I want to check that if $user model have group_id <= 4
//so they cannot change group_id when editing other users
public function update(User $user, UserGroup $userGroup)
{
return $user->group->id <= 4;
}
I registered this policy class in AuthService Provider 我在AuthService Provider中注册了此策略类
protected $policies = [
'App\User' => 'App\Policies\UserPolicy',
'App\UserGroup' => 'App\Policies\UserGroupPolicy',
'App\Team' => 'App\Policies\TeamPolicy',
'App\Branch' => 'App\Policies\BranchPolicy',
'App\Company' => 'App\Policies\CompanyPolicy',
];
But when testing I have many errors occur. 但是在测试时,会发生很多错误。
In the Controller 在控制器中
//For testing
public function index(Request $request)
{
//If I do not pass the user instance, like Laravel official document
//It will throw: : Too few arguments to function
//App\Policies\UserGroupPolicy::update(), 1 passed in
//path\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php
//on line 481 and exactly 2 expected
var_dump($request->user()->can('update', UserGroup::class));
//if I pass, it will always return true although I edit the update function
//in UserGroupPolicy class just return false
var_dump($request->user()->can('update', $request->user(), UserGroup::class));
}
So can anyone help me, thank you. 谁能帮助我,谢谢。
Try using 尝试使用
$this->authorize('update',UserGroup::class);
instead of 代替
$request->user()->can('update', UserGroup::class);
UPDATE :The second argument must be an instance of the UserGroup class and not the UserGroup class itself.So the correct code is UPDATE :第二个参数必须是UserGroup类的实例,而不是UserGroup类本身。因此正确的代码是
$this->authorize('update',$objectOfUserGroupClass);//and not the class itself
For more info check here 欲了解更多信息,请点击这里
It works for me.... 这个对我有用....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.