ChannelAbilityService.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\Channel;
  4. use App\Models\GroupMember;
  5. use App\Models\Share;
  6. use Illuminate\Auth\Access\AuthorizationException;
  7. use Illuminate\Contracts\Database\Query\Builder;
  8. use Illuminate\Support\Str;
  9. /**
  10. * channel 的权限判定(只给 v3 用):谁看得见、谁能写内容、谁能改信息、谁能删。
  11. *
  12. * 三种来源叠加:
  13. * 1. **拥有者**:owner 是本人 → 什么都能做
  14. * 2. **团队角色**:owner 是团队 → 按本人在团队里的角色({@see GroupAbilityService}):
  15. * reader 读;editor 读、写内容、改信息;manager 同 editor(另能在团队名下新建);owner 还能删
  16. * 3. **共享**(shares 表,直接共享给本人或本人所在的团队):power 10 读、20 写内容、30 改信息
  17. *
  18. * 「能访问」与「会被列出」是两回事:
  19. * - **能访问**({@see self::abilities()} 的 read):status ≥ 20 谁都能读——30 公开,20 公开不列出
  20. * (拿到链接就能看)。系统 channel(原文、系统术语等全站共用的基础数据)不论 status 也谁都能读——
  21. * 库里一半系统 channel 是 status 10,巴利原文 `_System_Pali_VRI_` 就是。
  22. * - **会被列出**({@see self::scopeListable()}):给别人看的列表只列 status 30 与系统 channel;
  23. * 20 只在拥有者、团队成员、被共享的人自己的列表里出现。
  24. * 系统 channel 不能改信息、不能删。
  25. * v2 的判定(`ShareApi`、`ChecksChannelEditPower` …)只认「owner 是本人」,不改它(铁律 2)。
  26. */
  27. class ChannelAbilityService
  28. {
  29. public const SHARE_CHANNEL = 2;
  30. public const POWER_READ = 10;
  31. public const POWER_WRITE = 20;
  32. public const POWER_MANAGE = 30;
  33. /** 能写内容的团队角色 */
  34. private const WRITER_ROLES = [GroupMember::ROLE_OWNER, GroupMember::ROLE_MANAGER, GroupMember::ROLE_EDITOR];
  35. public function __construct(private readonly GroupAbilityService $groups) {}
  36. /**
  37. * 本人对一个 channel 能做什么。
  38. *
  39. * @return array{read: bool, write: bool, update: bool, delete: bool}
  40. */
  41. public function abilities(Channel $channel, ?string $userUid): array
  42. {
  43. return $this->abilitiesMany([$channel], $userUid)[$channel->uid];
  44. }
  45. /**
  46. * 整页批量算:团队角色一次、共享权限一次,查询数与行数无关。
  47. *
  48. * @param iterable<Channel> $channels
  49. * @return array<string, array{read: bool, write: bool, update: bool, delete: bool}>
  50. */
  51. public function abilitiesMany(iterable $channels, ?string $userUid): array
  52. {
  53. $teams = $userUid ? $this->teamRoles($userUid) : [];
  54. $powers = [];
  55. if ($userUid) {
  56. $ids = [];
  57. foreach ($channels as $channel) {
  58. $ids[] = $channel->uid;
  59. }
  60. $powers = Share::whereIn('res_id', $ids)
  61. ->where('res_type', self::SHARE_CHANNEL)
  62. ->whereIn('cooperator_id', [$userUid, ...array_keys($teams)])
  63. ->selectRaw('res_id, max(power) as power')
  64. ->groupBy('res_id')
  65. ->pluck('power', 'res_id')
  66. ->all();
  67. }
  68. $result = [];
  69. foreach ($channels as $channel) {
  70. $read = (int) $channel->status >= Channel::STATUS_UNLISTED || (bool) $channel->is_system;
  71. $write = $update = $delete = false;
  72. if ($userUid !== null) {
  73. if ($channel->owner_uid === $userUid) {
  74. $write = $update = $delete = true;
  75. } else {
  76. $role = $teams[$channel->owner_uid] ?? null;
  77. $power = (int) ($powers[$channel->uid] ?? 0);
  78. $write = in_array($role, self::WRITER_ROLES, true) || $power >= self::POWER_WRITE;
  79. $update = GroupAbilityService::roleAllows($role, GroupAbilityService::UPDATE) || $power >= self::POWER_MANAGE;
  80. $delete = GroupAbilityService::roleAllows($role, GroupAbilityService::DELETE);
  81. $read = $read || $role !== null || $power >= self::POWER_READ;
  82. }
  83. }
  84. if ($channel->is_system) {
  85. $update = $delete = false;
  86. }
  87. $result[$channel->uid] = ['read' => $read || $write, 'write' => $write, 'update' => $update, 'delete' => $delete];
  88. }
  89. return $result;
  90. }
  91. /**
  92. * 读正文前的闸:channel 不存在(或已软删)404,看不见 403。
  93. *
  94. * 给按 channel 取正文的接口用(`tipitaka-reading`、`search/{id}` 的整章文档):
  95. * 私有 channel 只有拥有者、团队成员、被共享的人能读;公开与「公开不列出」谁都能读。
  96. *
  97. * @throws AuthorizationException
  98. */
  99. public function assertReadable(string $channelUid, ?string $userUid): void
  100. {
  101. $channel = Channel::query()
  102. ->where('uid', $channelUid)
  103. ->firstOrFail(['uid', 'owner_uid', 'status', 'is_system']);
  104. if (! $this->abilities($channel, $userUid)['read']) {
  105. throw new AuthorizationException(__('messages.channel_forbidden'));
  106. }
  107. }
  108. /**
  109. * 能不能在某个 studio(本人或团队)名下新建 channel。
  110. */
  111. public function canCreateIn(string $userUid, string $studioUid): bool
  112. {
  113. return $this->groups->can($userUid, $studioUid, GroupAbilityService::CREATE);
  114. }
  115. /**
  116. * 能不能看某个 studio(本人或团队)的工作区列表:本人,或该团队的任何成员。
  117. */
  118. public function canListStudio(string $userUid, string $studioUid): bool
  119. {
  120. return $this->groups->can($userUid, $studioUid, GroupAbilityService::READ);
  121. }
  122. /**
  123. * 查询约束:列表里列得出来的 channel——公开的(status 30)、系统的,加上(登录时)本人的、
  124. * 本人所在团队名下的、共享给本人或本人所在团队的。status 20(公开不列出)只在后三种里出现。
  125. *
  126. * @param string $table channels 表在查询里的名字(join 时可能带别名)
  127. */
  128. public function scopeListable(Builder $query, ?string $userUid, string $table = 'channels'): void
  129. {
  130. $query->where(function (Builder $q) use ($userUid, $table) {
  131. $q->where("{$table}.status", '>=', Channel::STATUS_PUBLIC)
  132. ->orWhere("{$table}.is_system", true);
  133. if ($userUid === null) {
  134. return;
  135. }
  136. $teams = $this->teamRoles($userUid);
  137. $q->orWhere("{$table}.owner_uid", $userUid);
  138. if ($teams !== []) {
  139. $q->orWhereIn("{$table}.owner_uid", array_keys($teams));
  140. }
  141. $shared = $this->sharedChannels([$userUid, ...array_keys($teams)], self::POWER_READ);
  142. if ($shared !== []) {
  143. $q->orWhereIn("{$table}.uid", $shared);
  144. }
  145. });
  146. }
  147. /**
  148. * 查询约束:能写内容的 channel(本人的、本人是团队 editor 及以上的团队名下的、共享权限 ≥20 的)。
  149. */
  150. public function scopeWritable(Builder $query, string $userUid, string $table = 'channels'): void
  151. {
  152. $teams = $this->teamRoles($userUid);
  153. $writerTeams = array_keys(array_filter($teams, fn (string $role) => in_array($role, self::WRITER_ROLES, true)));
  154. $shared = $this->sharedChannels([$userUid, ...array_keys($teams)], self::POWER_WRITE);
  155. $query->where(function (Builder $q) use ($userUid, $table, $writerTeams, $shared) {
  156. $q->where("{$table}.owner_uid", $userUid);
  157. if ($writerTeams !== []) {
  158. $q->orWhereIn("{$table}.owner_uid", $writerTeams);
  159. }
  160. if ($shared !== []) {
  161. $q->orWhereIn("{$table}.uid", $shared);
  162. }
  163. });
  164. }
  165. /**
  166. * 直接共享给某个 studio(本人或团队,**不含**经团队转来的)的 channel uid。
  167. *
  168. * @return list<string>
  169. */
  170. public function sharedTo(string $studioUid): array
  171. {
  172. return $this->sharedChannels([$studioUid], self::POWER_READ);
  173. }
  174. /**
  175. * 本人所在的团队 → 角色。
  176. *
  177. * @return array<string, string>
  178. */
  179. private function teamRoles(string $userUid): array
  180. {
  181. $roles = [];
  182. foreach (GroupMember::where('user_id', $userUid)->get(['group_id', 'role', 'power']) as $member) {
  183. $roles[$member->group_id] = $member->effectiveRole();
  184. }
  185. return $roles;
  186. }
  187. /**
  188. * 共享给这些人 / 团队、且权限不低于 $minPower 的 channel uid。
  189. *
  190. * @param list<string> $cooperators
  191. * @return list<string>
  192. */
  193. private function sharedChannels(array $cooperators, int $minPower): array
  194. {
  195. return Share::whereIn('cooperator_id', $cooperators)
  196. ->where('res_type', self::SHARE_CHANNEL)
  197. ->where('power', '>=', $minPower)
  198. ->pluck('res_id')
  199. // shares.res_id 是 varchar,channels.uid 是 uuid;非法值进了 where 会让 pgsql 报错
  200. ->filter(fn ($id) => Str::isUuid($id))
  201. ->unique()
  202. ->values()
  203. ->all();
  204. }
  205. }