ChannelAbilityService.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. * 能不能往某个 channel 写内容(句子、批注等)。channel 不存在或已软删按不能写。
  110. */
  111. public function canWrite(string $channelUid, string $userUid): bool
  112. {
  113. $channel = Channel::query()
  114. ->where('uid', $channelUid)
  115. ->first(['uid', 'owner_uid', 'status', 'is_system']);
  116. return $channel !== null && $this->abilities($channel, $userUid)['write'];
  117. }
  118. /**
  119. * 本人能写内容的全部 channel uid({@see self::scopeWritable()} 的结果)。
  120. *
  121. * @return list<string>
  122. */
  123. public function writableUids(string $userUid): array
  124. {
  125. $query = Channel::query();
  126. $this->scopeWritable($query, $userUid);
  127. return $query->pluck('uid')->map(fn ($uid) => (string) $uid)->all();
  128. }
  129. /**
  130. * 能不能在某个 studio(本人或团队)名下新建 channel。
  131. */
  132. public function canCreateIn(string $userUid, string $studioUid): bool
  133. {
  134. return $this->groups->can($userUid, $studioUid, GroupAbilityService::CREATE);
  135. }
  136. /**
  137. * 能不能看某个 studio(本人或团队)的工作区列表:本人,或该团队的任何成员。
  138. */
  139. public function canListStudio(string $userUid, string $studioUid): bool
  140. {
  141. return $this->groups->can($userUid, $studioUid, GroupAbilityService::READ);
  142. }
  143. /**
  144. * 查询约束:列表里列得出来的 channel——公开的(status 30)、系统的,加上(登录时)本人的、
  145. * 本人所在团队名下的、共享给本人或本人所在团队的。status 20(公开不列出)只在后三种里出现。
  146. *
  147. * @param string $table channels 表在查询里的名字(join 时可能带别名)
  148. */
  149. public function scopeListable(Builder $query, ?string $userUid, string $table = 'channels'): void
  150. {
  151. $query->where(function (Builder $q) use ($userUid, $table) {
  152. $q->where("{$table}.status", '>=', Channel::STATUS_PUBLIC)
  153. ->orWhere("{$table}.is_system", true);
  154. if ($userUid === null) {
  155. return;
  156. }
  157. $teams = $this->teamRoles($userUid);
  158. $q->orWhere("{$table}.owner_uid", $userUid);
  159. if ($teams !== []) {
  160. $q->orWhereIn("{$table}.owner_uid", array_keys($teams));
  161. }
  162. $shared = $this->sharedChannels([$userUid, ...array_keys($teams)], self::POWER_READ);
  163. if ($shared !== []) {
  164. $q->orWhereIn("{$table}.uid", $shared);
  165. }
  166. });
  167. }
  168. /**
  169. * 查询约束:能写内容的 channel(本人的、本人是团队 editor 及以上的团队名下的、共享权限 ≥20 的)。
  170. */
  171. public function scopeWritable(Builder $query, string $userUid, string $table = 'channels'): void
  172. {
  173. $teams = $this->teamRoles($userUid);
  174. $writerTeams = array_keys(array_filter($teams, fn (string $role) => in_array($role, self::WRITER_ROLES, true)));
  175. $shared = $this->sharedChannels([$userUid, ...array_keys($teams)], self::POWER_WRITE);
  176. $query->where(function (Builder $q) use ($userUid, $table, $writerTeams, $shared) {
  177. $q->where("{$table}.owner_uid", $userUid);
  178. if ($writerTeams !== []) {
  179. $q->orWhereIn("{$table}.owner_uid", $writerTeams);
  180. }
  181. if ($shared !== []) {
  182. $q->orWhereIn("{$table}.uid", $shared);
  183. }
  184. });
  185. }
  186. /**
  187. * 直接共享给某个 studio(本人或团队,**不含**经团队转来的)的 channel uid。
  188. *
  189. * @return list<string>
  190. */
  191. public function sharedTo(string $studioUid): array
  192. {
  193. return $this->sharedChannels([$studioUid], self::POWER_READ);
  194. }
  195. /**
  196. * 本人所在的团队 → 角色。
  197. *
  198. * @return array<string, string>
  199. */
  200. private function teamRoles(string $userUid): array
  201. {
  202. $roles = [];
  203. foreach (GroupMember::where('user_id', $userUid)->get(['group_id', 'role', 'power']) as $member) {
  204. $roles[$member->group_id] = $member->effectiveRole();
  205. }
  206. return $roles;
  207. }
  208. /**
  209. * 共享给这些人 / 团队、且权限不低于 $minPower 的 channel uid。
  210. *
  211. * @param list<string> $cooperators
  212. * @return list<string>
  213. */
  214. private function sharedChannels(array $cooperators, int $minPower): array
  215. {
  216. return Share::whereIn('cooperator_id', $cooperators)
  217. ->where('res_type', self::SHARE_CHANNEL)
  218. ->where('power', '>=', $minPower)
  219. ->pluck('res_id')
  220. // shares.res_id 是 varchar,channels.uid 是 uuid;非法值进了 where 会让 pgsql 报错
  221. ->filter(fn ($id) => Str::isUuid($id))
  222. ->unique()
  223. ->values()
  224. ->all();
  225. }
  226. }