GroupAbilityService.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\GroupMember;
  4. /**
  5. * 团队空间的权限判定:「某人对某个 owner 名下的资源能做什么」。
  6. *
  7. * owner 是本人 → 什么都能做;owner 是一个团队 → 按此人在团队里的角色查表;
  8. * 其余 → 什么都不能做。资源自己的协作(share 表)不在这里管,由各资源的 Service 叠加。
  9. *
  10. * 只给 v3 用。v2 的权限判定(`ShareApi`、`ChecksChannelEditPower` …)只认
  11. * 「owner 就是本人」,不改它——见 CLAUDE.md 铁律 2。
  12. */
  13. class GroupAbilityService
  14. {
  15. /** 看得到 owner 名下的资源 */
  16. public const READ = 'read';
  17. /** 在 owner 名下新建资源 */
  18. public const CREATE = 'create';
  19. /** 修改 owner 名下的资源(含 channel 里的译文、术语等内容) */
  20. public const UPDATE = 'update';
  21. /** 删除 owner 名下的资源 */
  22. public const DELETE = 'delete';
  23. /** 加人、移人、改成员角色 */
  24. public const MANAGE_MEMBERS = 'manage_members';
  25. /** 改团队本身的名称、简介、公开状态;从团队文档里移除共享 */
  26. public const MANAGE_GROUP = 'manage_group';
  27. /** 删除团队本身(区别于删除团队名下的资源) */
  28. public const DELETE_GROUP = 'delete_group';
  29. /** @var array<string, list<string>> */
  30. private const ABILITIES = [
  31. GroupMember::ROLE_OWNER => [
  32. self::READ, self::CREATE, self::UPDATE, self::DELETE,
  33. self::MANAGE_MEMBERS, self::MANAGE_GROUP, self::DELETE_GROUP,
  34. ],
  35. GroupMember::ROLE_MANAGER => [self::READ, self::CREATE, self::UPDATE, self::MANAGE_MEMBERS, self::MANAGE_GROUP],
  36. GroupMember::ROLE_EDITOR => [self::READ, self::UPDATE],
  37. GroupMember::ROLE_READER => [self::READ],
  38. ];
  39. /**
  40. * 某人对某个 owner(用户或团队的 uuid)能不能做某件事。
  41. */
  42. public function can(string $userUid, string $ownerUid, string $ability): bool
  43. {
  44. if ($userUid === $ownerUid) {
  45. return true;
  46. }
  47. return self::roleAllows($this->roleIn($userUid, $ownerUid), $ability);
  48. }
  49. /**
  50. * 此人在团队里的角色;不是成员(或 owner 根本不是团队)返回 null。
  51. */
  52. public function roleIn(string $userUid, string $groupUid): ?string
  53. {
  54. return $this->membership($userUid, $groupUid)?->effectiveRole();
  55. }
  56. /**
  57. * 此人在团队里的成员记录;不是成员返回 null。
  58. */
  59. public function membership(string $userUid, string $groupUid): ?GroupMember
  60. {
  61. // 不做缓存:控制器实例会被路由缓存、Service 跟着跨请求存活,缓存会让改过的角色迟迟不生效
  62. return GroupMember::where('group_id', $groupUid)
  63. ->where('user_id', $userUid)
  64. ->first();
  65. }
  66. /**
  67. * 角色是否包含某项能力。null(不是成员)一律不包含。
  68. */
  69. public static function roleAllows(?string $role, string $ability): bool
  70. {
  71. return $role !== null && in_array($ability, self::ABILITIES[$role] ?? [], true);
  72. }
  73. }