我使用laravel-backpack管理员来管理我的应用程序的管理部分,并使用PermissionManager来管理用户角色和权限。现在,我想分配对特定数据的特定访问权限。
例如,假设我们有一个文章管理系统,并且对于用户名为user24的用户,我们有一个editor角色及其相关权限,因此所需的方式是user24必须访问其仪表板或crud列表中的特定文章,如article 1。
Articles表的结构:
注意:'user_id‘字段是指文章的所有者。
|---------------------|------------------|------------------|
| id | title | user_id |
|---------------------|------------------|------------------|
| 1 | article1 | 2 |
|---------------------|------------------|------------------|发布于 2020-09-20 22:03:23
方法1:
要实现这一点,一种方法是创建第二个名为CrudArticle (或其他任何东西)的类,使其扩展原始的文章类,然后向该模型添加一个全局作用域,该作用域将使用该类对表的所有查询限制为只包括属于当前用户的记录。将此类与CRUD面板一起使用,并在应用程序中的其他位置使用普通的文章类。
class CrudArticle extends Article {
public static function boot()
{
parent::boot();
// only include models that belong to this user
$user_id = 0;
Auth::check();
if ($user = Auth::user()) {
$user_id = $user->id;
}
static::addGlobalScope('userFilter', static function (Builder $builder) use ($user_id){
$builder->where('user_id', $user_id);
});
}
}注意:这将阻止非拥有记录出现在列表页面上,并阻止通过直接url加载编辑页面。然而,我不能100%确定上面的操作是否可以防止插入(直接向更新端点发送请求),也就是说,您可能仍然需要对下面第二种可能的解决方案中推荐的"UpdateRequest“进行更改
方法2:
另一种实现方法是修改CRUD使用的查询,例如,在您的CRUD控制器中:
/**
* Set up the "list" or "read" operation for the resource
*/
public function setupListOperation(): void
{
// ... normal setup code ...
Auth::check();
$user = Auth::user();
if (!$user) {
throw new \Exception('Unauthorized');
}
$this->crud->query = $this->crud->query->where('user_id', $user->id);
}为了防止通过直接url查看更新页面,您可以在setupUpdateOperation中添加类似以下内容:
/**
* Set up the "update" operation for the resource
*/
public function setupUpdateOperation(): void
{
// ... normal setup code ...
$authorized = false;
// only allow viewing the update page if the user is logged in and owns the Article
Auth::check();
if ($user = Auth::user()) {
$id = $this->get('id');
$product = Article::find($id);
if ($product) {
$authorized = $product->user_id === $user->id;
}
}
if (!$authorized) {
$this->crud->denyAccess(['update']);
}
}为了防止未经授权的编辑直接发布到更新端点,您还需要在UpdateRequest中添加类似以下内容的内容:
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
$authorized = false;
// only allow updates if the user is logged in and owns the Article
Auth::check();
if ($user = Auth::user()) {
$id = $this->get('id');
$product = Article::find($id);
if ($product) {
$authorized = $product->user_id === $user->id;
}
}
return $authorized;
}或者,你也可以使用add a global scope to the model in question as explained here,尽管我倾向于避免这样做,因为它会改变整个应用的行为
https://stackoverflow.com/questions/63978797
复制相似问题