LikeAdminAllowMiddleware.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. if($firstSegment === 'tenantapi'){
  64. return $this->handleTenantAccess($tenantModel, $domain, $request, $next, true);
  65. }else{
  66. return $this->apiHandle($request, $next);
  67. }
  68. }
  69. /**
  70. * 设置跨域头信息
  71. */
  72. private function setCorsHeaders()
  73. {
  74. $headers = [
  75. 'Access-Control-Allow-Origin' => '*',
  76. 'Access-Control-Allow-Headers' => implode(', ', self::ALLOWED_HEADERS),
  77. 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, post',
  78. 'Access-Control-Max-Age' => '1728000',
  79. 'Access-Control-Allow-Credentials' => 'true'
  80. ];
  81. foreach ($headers as $key => $value) {
  82. header("$key: $value");
  83. }
  84. }
  85. /**
  86. * @notes 处理租户访问逻辑
  87. * @param Tenant $tenantModel
  88. * @param string $domain
  89. * @param $request
  90. * @param Closure $next
  91. * @param bool $isPage
  92. * @return mixed|\think\Response|\think\response\Json|\think\response\View
  93. * @author JXDN
  94. * @date 2024/09/11 14:06
  95. */
  96. private function handleTenantAccess(Tenant $tenantModel, string $domain, $request, Closure $next, bool $isPage = false)
  97. {
  98. // 通过别名访问租户
  99. $tenant = $tenantModel->where(['domain_alias' => $domain])->findOrEmpty();
  100. if (!$tenant->isEmpty() && $tenant->disable === 0 && $tenant->domain_alias_enable === 0) {
  101. $request->tenantId = $tenant->id;
  102. $request->tenantSn = $tenant->sn;
  103. return $next($request);
  104. } elseif (!$tenant->isEmpty()) {
  105. return $this->tenantDisabledResponse($isPage);
  106. }
  107. // 通过子域名访问租户
  108. $request->tenantSn = $request->subDomain();
  109. $tenant = $tenantModel->where(['sn' => $request->tenantSn])->findOrEmpty();
  110. if (!$tenant->isEmpty()) {
  111. if ($tenant->disable === 0) {
  112. $request->tenantId = $tenant->id;
  113. return $next($request);
  114. } else {
  115. return $this->tenantDisabledResponse($isPage);
  116. }
  117. }
  118. // 租户不存在或域名错误
  119. return $isPage ? view(app()->getRootPath() . 'public/error/tenant/404.html') : JsonService::fail('接口域名错误或代理商不存在', [], 4, 0);
  120. }
  121. /**
  122. * @notes 返回租户停用的响应
  123. * @param bool $isPage
  124. * @return \think\response\Json|\think\response\View
  125. * @author JXDN
  126. * @date 2024/09/11 14:06
  127. */
  128. private function tenantDisabledResponse(bool $isPage)
  129. {
  130. return $isPage ? view(app()->getRootPath() . 'public/error/tenant/403.html') : JsonService::fail('该租户已停用', [], 3, 0);
  131. }
  132. public function apiHandle($request, Closure $next, ?array $header = [])
  133. {
  134. header('Access-Control-Allow-Origin: *');
  135. header("Access-Control-Allow-Headers: Authorization, Sec-Fetch-Mode, DNT, X-Mx-ReqToken, Keep-Alive, User-Agent, If-Match, If-None-Match, If-Unmodified-Since, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Accept-Language, Origin, Accept-Encoding,Access-Token,token,version");
  136. header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, post');
  137. header('Access-Control-Max-Age: 1728000');
  138. header('Access-Control-Allow-Credentials:true');
  139. if (strtoupper($request->method()) == "OPTIONS") {
  140. return response();
  141. }
  142. return $next($request);
  143. }
  144. }