【发布时间】:2021-12-04 09:36:52
【问题描述】:
我正在开发一个有客户和管理员的 Laravel 8 项目。如果管理员的角色是superadmin,则允许管理员查看我的ManagementController 中的数据。我的users 表上有一个role 列作为enum 值,并且已经注册了我的策略,但无论角色如何,它总是返回403 和我的消息,我做错了什么。
我的政策是:
<?php
namespace App\Policies;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class ManagementPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the model.
*
* @param \App\User $user
* @return mixed
*/
public function view(User $user)
{
return $user->role == 'superadmin';
}
}
注册我的保单:
protected $policies = [
User::class => ManagementPolicy::class
];
然后在我的index 函数中,我确定用户是否无法查看资源,然后返回:
if (Auth::user()->cant('view', User::class)) {
return response()->json([
'success' => false,
'message' => 'not allowed',
'role' => Auth::user()->role
], 403);
}
【问题讨论】:
-
在策略检查中尝试使用 cannot 而不是 cant
-
似乎只适用于
Managemnt::class作为秒 arg,我的控制器列在app/Http/Controllers/Management/DashboardController下,所以不确定为什么它与不存在的类一起使用?
标签: php laravel authentication