PermissionService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * @Name
  4. * @Description
  5. * @Author 刘学玺
  6. * @Date 2024/8/18 22:44
  7. */
  8. namespace App\Http\Services\Backend\Server\System;
  9. use App\Enums\System\Role\DataScope;
  10. use App\Exceptions\ApiException;
  11. use App\Http\Services\Service;
  12. use App\Models\System\Menu;
  13. use App\Models\System\Role;
  14. use App\Models\System\User;
  15. use Illuminate\Support\Collection;
  16. use Ramsey\Uuid\Type\Integer;
  17. use Spatie\Permission\Guard;
  18. use Spatie\Permission\Models\Permission;
  19. use Symfony\Component\HttpFoundation\Response;
  20. class PermissionService extends Service
  21. {
  22. /**
  23. * @throws ApiException
  24. */
  25. public function assignPermission($params, $id): void
  26. {
  27. match ($params['type']) {
  28. 'role' => $this->assignRolePermission($params, $id),
  29. 'model' => $this->assignModelPermission($params, $id),
  30. default => self::error('PARAMS_TYPE_ERROR', Response::HTTP_UNPROCESSABLE_ENTITY)
  31. };
  32. }
  33. /**
  34. * @throws ApiException
  35. */
  36. public function assignRolePermission($params, $id): void
  37. {
  38. $params['guard_name'] = $params['guard_name'] ?? Guard::getDefaultName(static::class);
  39. // 获取角色
  40. $role = Role::findById($id);// query()->where('guard_name', $params['guard_name'])->find($id);
  41. !$role && self::error('ROLE_NOT_EXISTS', Response::HTTP_UNPROCESSABLE_ENTITY);
  42. // 清空菜单与角色的关联
  43. $menus = $role->menus;
  44. foreach ($menus as $menu) {
  45. $menu->removeRole($role->name);
  46. }
  47. // 添加菜单与角色的关联
  48. $syncMenus = Menu::query()->whereIn('id', $params['permission'])->get();
  49. $permissions = collect([]);
  50. foreach ($syncMenus as $menu) {
  51. // 添加菜单与角色的关联
  52. $menu->assignRole($role);
  53. // 获取菜单权限
  54. if (!$menu->permissions->isEmpty()) $permissions = $permissions->merge($menu->permissions);
  55. }
  56. // 给角色添加多个权限
  57. $role->syncPermissions($permissions);
  58. // 记录操作日志上下文
  59. // LogRecordContext.putVariable("role", role);
  60. // return role.getId();
  61. }
  62. public function assignModelPermission($params, $id)
  63. {
  64. }
  65. public function getPermissions(int $id, string $class)
  66. {
  67. $classInstance = app($class);
  68. // 角色类型
  69. if ($class === Role::class) {
  70. $role = $classInstance::findById($id);
  71. return $role->menus->pluck('id');
  72. }
  73. return [];
  74. }
  75. // 获取用户角色
  76. public function getUserRoles(int $id): Collection
  77. {
  78. return User::query()->find($id)->roles->pluck('id');
  79. }
  80. // 分配用户角色
  81. public function assignUserRole(array $data): void
  82. {
  83. $user = User::query()->find($data['userId']);
  84. $user->roles()->sync($data['roleIds']);
  85. }
  86. }