AdminRealtimeAccess.php 5.1 KB

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