LikeAdminAllowMiddleware.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeadmin快速开发前后端分离管理后台(PHP版)
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
  8. // | github下载:https://github.com/likeshop-github/likeadmin
  9. // | 访问官网:https://www.likeadmin.cn
  10. // | likeadmin团队 版权所有 拥有最终解释权
  11. // +----------------------------------------------------------------------
  12. // | author: likeadminTeam
  13. // +----------------------------------------------------------------------
  14. declare (strict_types=1);
  15. namespace app\common\http\middleware;
  16. use app\common\model\tenant\Tenant;
  17. use app\common\service\JsonService;
  18. use Closure;
  19. use think\facade\Config;
  20. /**
  21. * 自定义跨域中间件
  22. * Class LikeAdminAllowMiddleware
  23. * @package app\common\http\middleware
  24. */
  25. class LikeAdminAllowMiddleware
  26. {
  27. /**
  28. * 允许的请求头常量
  29. */
  30. private const ALLOWED_HEADERS = [
  31. 'Authorization', 'Sec-Fetch-Mode', 'DNT', 'X-Mx-ReqToken', 'Keep-Alive', 'User-Agent',
  32. 'If-Match', 'If-None-Match', 'If-Unmodified-Since', 'X-Requested-With', 'If-Modified-Since',
  33. 'Cache-Control', 'Content-Type', 'Accept-Language', 'Origin', 'Accept-Encoding', 'Access-Token',
  34. 'token', 'version'
  35. ];
  36. /**
  37. * @notes 跨域处理
  38. * @param $request
  39. * @param Closure $next
  40. * @param array|null $header
  41. * @return mixed|\think\Response|\think\response\Json|\think\response\View
  42. * @author JXDN
  43. * @date 2024/09/11 14:11
  44. */
  45. public function handle($request, Closure $next, ?array $header = [])
  46. {
  47. // 设置跨域头
  48. $this->setCorsHeaders();
  49. // 如果是OPTIONS请求,直接返回响应
  50. if (strtoupper($request->method()) === 'OPTIONS') {
  51. return response();
  52. }
  53. // 安装检测
  54. $install = file_exists(root_path() . '/config/install.lock');
  55. if (!$install) {
  56. return JsonService::fail('程序未安装', [], -2);
  57. }
  58. // 获取租户信息
  59. $tenantModel = new Tenant();
  60. $domain = preg_replace('/^https?:\/\/|\/$/', '', $request->domain());
  61. $pathSegments = explode('/', $request->pathinfo());
  62. $firstSegment = $pathSegments[0];
  63. // 处理API请求
  64. if (str_contains($firstSegment, 'api')) {
  65. if ($firstSegment !== 'adminapi') {
  66. return $this->handleTenantAccess($tenantModel, $domain, $request, $next);
  67. }
  68. } else {
  69. // 处理页面请求
  70. if ($firstSegment !== 'admin') {
  71. return $this->handleTenantAccess($tenantModel, $domain, $request, $next, true);
  72. } else {
  73. if ($domain !== Config::get('project.http_host')) {
  74. return view(app()->getRootPath() . 'public/error/platform/404.html');
  75. }
  76. }
  77. }
  78. return $next($request);
  79. }
  80. /**
  81. * 设置跨域头信息
  82. */
  83. private function setCorsHeaders()
  84. {
  85. $headers = [
  86. 'Access-Control-Allow-Origin' => '*',
  87. 'Access-Control-Allow-Headers' => implode(', ', self::ALLOWED_HEADERS),
  88. 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, post',
  89. 'Access-Control-Max-Age' => '1728000',
  90. 'Access-Control-Allow-Credentials' => 'true'
  91. ];
  92. foreach ($headers as $key => $value) {
  93. header("$key: $value");
  94. }
  95. }
  96. /**
  97. * @notes 处理租户访问逻辑
  98. * @param Tenant $tenantModel
  99. * @param string $domain
  100. * @param $request
  101. * @param Closure $next
  102. * @param bool $isPage
  103. * @return mixed|\think\Response|\think\response\Json|\think\response\View
  104. * @author JXDN
  105. * @date 2024/09/11 14:06
  106. */
  107. private function handleTenantAccess(Tenant $tenantModel, string $domain, $request, Closure $next, bool $isPage = false)
  108. {
  109. // 通过别名访问租户
  110. $tenant = $tenantModel->where(['domain_alias' => $domain])->findOrEmpty();
  111. if (!$tenant->isEmpty() && $tenant->disable === 0 && $tenant->domain_alias_enable === 0) {
  112. $request->tenantId = $tenant->id;
  113. $request->tenantSn = $tenant->sn;
  114. return $next($request);
  115. } elseif (!$tenant->isEmpty()) {
  116. return $this->tenantDisabledResponse($isPage);
  117. }
  118. // 通过子域名访问租户
  119. $request->tenantSn = $request->subDomain();
  120. $tenant = $tenantModel->where(['sn' => $request->tenantSn])->findOrEmpty();
  121. if (!$tenant->isEmpty()) {
  122. if ($tenant->disable === 0) {
  123. $request->tenantId = $tenant->id;
  124. return $next($request);
  125. } else {
  126. return $this->tenantDisabledResponse($isPage);
  127. }
  128. }
  129. // 租户不存在或域名错误
  130. return $isPage ? view(app()->getRootPath() . 'public/error/tenant/404.html') : JsonService::fail('接口域名错误或租户不存在', [], 4, 0);
  131. }
  132. /**
  133. * @notes 返回租户停用的响应
  134. * @param bool $isPage
  135. * @return \think\response\Json|\think\response\View
  136. * @author JXDN
  137. * @date 2024/09/11 14:06
  138. */
  139. private function tenantDisabledResponse(bool $isPage)
  140. {
  141. return $isPage ? view(app()->getRootPath() . 'public/error/tenant/403.html') : JsonService::fail('该租户已停用', [], 3, 0);
  142. }
  143. }