AdminRealtimeAccess.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. <?php
  2. namespace App\Services\AdminRealtime;
  3. use App\Services\MenuService;
  4. use App\Services\RoleService;
  5. use App\Services\RoleUserService;
  6. use Illuminate\Support\Facades\Broadcast;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\Log;
  9. use Pusher\Pusher;
  10. use RuntimeException;
  11. /**
  12. * 后台实时推送的访问控制:频道授权与登录过期断开。
  13. *
  14. * 频道授权响应在 channel_data 中携带「会话 user_id」(管理员 id + JWT 过期时间),Reverb 把它记在连接上;
  15. * relay 定期把已过期的会话登记出来,调用 Reverb 的 terminate 接口断开这些连接。
  16. * 断开后前端自动重连会重新授权,过期的 JWT 授权失败(401),前端据此跳转登录。
  17. */
  18. final class AdminRealtimeAccess
  19. {
  20. private const SESSIONS = 'admin_realtime:sessions';
  21. /** @return list<string> 管理员可订阅的频道,口径与 CheckButtonPermission 对列表接口的按钮权限一致 */
  22. public static function allowedChannels(int $adminId): array
  23. {
  24. $ttl = max(0, (int) config('admin_realtime.permission_cache_seconds', 60));
  25. if ($ttl === 0) {
  26. return self::resolveChannels($adminId);
  27. }
  28. return Cache::remember('admin_realtime:channels:' . $adminId, $ttl, static fn(): array => self::resolveChannels($adminId));
  29. }
  30. private static function resolveChannels(int $adminId): array
  31. {
  32. $channels = array_keys(AdminRealtimeRows::CHANNELS);
  33. if ($adminId === 1) {
  34. return $channels;
  35. }
  36. if (!in_array($adminId, config('agent.admin_ids', [1]), true)) {
  37. $channels = array_values(array_diff($channels, AdminRealtimeRows::AGENT_CHANNELS));
  38. }
  39. $roleIds = collect(RoleUserService::findAll(['user_id' => $adminId]))->pluck('role_id')->toArray() ?: [-1];
  40. $granted = [];
  41. foreach (RoleService::model()::with(['menus' => function ($query) {
  42. $query->where('type', MenuService::model()::TYPE_BUTTON);
  43. }])->whereIn('id', $roleIds)->get() as $role) {
  44. $granted = array_merge($granted, $role['menus_uris'] ?: []);
  45. }
  46. return array_values(array_filter($channels, static function (string $channel) use ($granted): bool {
  47. $uri = AdminRealtimeRows::CHANNELS[$channel][1];
  48. $menu = MenuService::findOne(['uri' => $uri, 'type' => MenuService::model()::TYPE_BUTTON, 'status' => MenuService::model()::STATUS_SHOW]);
  49. return empty($menu) || in_array($uri, $granted, true);
  50. }));
  51. }
  52. /**
  53. * Pusher 协议私有频道授权,返回 {auth, channel_data}
  54. *
  55. * @param string $channelName 带 private- 前缀的频道名
  56. * @throws \Pusher\PusherException socket_id 或频道名格式不合法
  57. */
  58. public static function authorize(int $adminId, ?int $sessionExpiresAt, string $channelName, string $socketId): array
  59. {
  60. if (!$sessionExpiresAt) {
  61. throw new RuntimeException('后台推送要求 JWT 带有过期时间');
  62. }
  63. $userId = self::sessionUserId($adminId, $sessionExpiresAt);
  64. $auth = self::pusher()->authorizeChannel($channelName, $socketId, json_encode(['user_id' => $userId]));
  65. if ($sessionExpiresAt) {
  66. self::rememberSession($userId, $sessionExpiresAt);
  67. }
  68. return json_decode($auth, true);
  69. }
  70. public static function sessionUserId(int $adminId, ?int $sessionExpiresAt): string
  71. {
  72. return $adminId . ':' . (int) $sessionExpiresAt;
  73. }
  74. /** 断开 JWT 已过期的会话,由 relay 定期调用;返回断开的会话 user_id */
  75. public static function terminateExpiredSessions(): array
  76. {
  77. $sessions = Cache::get(self::SESSIONS, []);
  78. $terminated = [];
  79. foreach ($sessions as $userId => $exp) {
  80. if ($exp > time()) continue;
  81. try {
  82. self::pusher()->terminateUserConnections((string) $userId);
  83. $terminated[(string) $userId] = $exp;
  84. } catch (\Throwable $e) {
  85. Log::channel('realtime')->error('admin_realtime_terminate_failed', ['user_id' => $userId, 'error' => $e->getMessage()]);
  86. }
  87. }
  88. if ($terminated) {
  89. Cache::lock(self::SESSIONS . ':lock', 5)->block(3, function () use ($terminated) {
  90. $current = Cache::get(self::SESSIONS, []);
  91. foreach ($terminated as $userId => $exp) {
  92. if (($current[$userId] ?? null) === $exp) unset($current[$userId]);
  93. }
  94. if (!Cache::forever(self::SESSIONS, $current)) {
  95. throw new RuntimeException('保存后台推送会话状态失败');
  96. }
  97. });
  98. }
  99. return array_keys($terminated);
  100. }
  101. /** 同一会话订阅多个频道会重复授权,已登记的不再加锁写缓存 */
  102. private static function rememberSession(string $userId, int $exp): void
  103. {
  104. if (isset(Cache::get(self::SESSIONS, [])[$userId])) {
  105. return;
  106. }
  107. Cache::lock(self::SESSIONS . ':lock', 5)->block(3, function () use ($userId, $exp) {
  108. $sessions = Cache::get(self::SESSIONS, []);
  109. $sessions[$userId] = $exp;
  110. if (!Cache::forever(self::SESSIONS, $sessions)) {
  111. throw new RuntimeException('登记后台推送会话失败');
  112. }
  113. });
  114. }
  115. private static function pusher(): Pusher
  116. {
  117. return Broadcast::connection(config('admin_realtime.connection'))->getPusher();
  118. }
  119. }