0

我是 Laravel 的新手,我想通过 RESTFUL API 使我的数据库中的数据可用。我需要控制具有字段级别特异性的数据对象的权限。我很好奇在 Laravel 中这样做的惯用方式是什么?

例如,我将有一个名为的数据库表PrintMachine,其中包含字段Id,MachineName,ActivityStatus,ManufacturingYear。我想分配以下权限:

  • Web 管理员获得对所有记录和所有字段的读取和编辑权限PrintMachine
  • PrintMachine.MachineName and PrintMachine.ActivityStatus工厂经理对所有记录的字段具有读取和编辑权限,而对PrintMachine.
  • 楼层操作员获得对所有记录的字段的读取访问权限,PrintMachine.MachineName并且无权访问 中的任何其他字段PrintMachine

人们告诉我考虑Spatie 模块并阅读Gates 和 Policies,但目前尚不清楚两者如何自行实现字段级别权限。

我正在考虑的另一个选择是通过以下方式自定义创建自己的解决方案:

  • 对于 GET 请求,创建三个名为 的 ViewModel PrintMachineAdmin,PrintMachineManager,PrintMachineOperator,每个类都具有可供相应角色访问的属性。
  • 对于 POST/PUT 请求,我必须编写自己的条件语句来根据用户角色验证数据

是否有更惯用的方法来开发用于 RESTful API 的字段级权限功能?

4

1 回答 1

0

这么多选择。角色和权限结构的实现可以实现这一点,您当然可以通过 Spatie 模块做到这一点。

例如改编自 spatie 文档:

$role = Role::create(['name' => 'Manager']); //db has roles table
//or if already created 
//$role = Role::where('name', 'Manager')->first();

$permission = Permission::create(['name' => 'edit PrintMachine.MachineName']); //db permissions table

$role->givePermissionTo($permission); //now manager role has been assigned permission to edit machine name.

//assigning role to user
$user = User::create(['name'=> 'Manager User']); //or get existing
$user->assigneRole($role); //now this user has edit access to machine name

//to see if user has access
if( $user->hasPermissionTo('edit PrintMachine.MachineName') )
  //do efit
//OR if you want to check using role
if( $user->hasRole('Manager')
  //do manager stuff

//and in view you can use @can blade directive
@can( 'edit PrintMachine.MachineName' )
  //authenticated user can edit machine name //show edit button/form
@endcan
//similarly @role directive will do the check using role

对于AuthServiceProvider'sboot方法中的超级管理员。

Gate::before(function ($user, $ability) {
 return $user->hasRole('Super Admin') ? true : null;
});

Gate 的before方法先于所有其他 Gate 操作,因此可以在此处覆盖所有其他权限。

于 2020-08-21T04:01:33.307 回答