LikeAdminAllowMiddleware.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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\service\JsonService;
  17. use Closure;
  18. /**
  19. * 自定义跨域中间件
  20. * Class LikeAdminAllowMiddleware
  21. * @package app\common\http\middleware
  22. */
  23. class LikeAdminAllowMiddleware
  24. {
  25. /**
  26. * 允许的请求头常量
  27. */
  28. private const ALLOWED_HEADERS = [
  29. 'Authorization', 'Sec-Fetch-Mode', 'DNT', 'X-Mx-ReqToken', 'Keep-Alive', 'User-Agent',
  30. 'If-Match', 'If-None-Match', 'If-Unmodified-Since', 'X-Requested-With', 'If-Modified-Since',
  31. 'Cache-Control', 'Content-Type', 'Accept-Language', 'Origin', 'Accept-Encoding', 'Access-Token',
  32. 'token', 'version'
  33. ];
  34. /**
  35. * @notes 跨域处理
  36. * @param $request
  37. * @param \Closure $next
  38. * @param array|null $header
  39. * @return mixed|\think\Response
  40. * @author 令狐冲
  41. * @date 2021/7/26 11:51
  42. */
  43. public function handle($request, Closure $next, ?array $header = []): mixed
  44. {
  45. // 设置跨域头
  46. $this->setCorsHeaders();
  47. // 如果是OPTIONS请求,直接返回响应
  48. if (strtoupper($request->method()) === 'OPTIONS') {
  49. return response();
  50. }
  51. // 安装检测
  52. $install = file_exists(root_path() . '/config/install.lock');
  53. if (!$install) {
  54. return JsonService::fail('程序未安装', [], -2);
  55. }
  56. return $next($request);
  57. }
  58. /**
  59. * @notes 设置跨域头信息
  60. * @return void
  61. * @author JXDN
  62. * @date 2024/09/24 16:35
  63. */
  64. private function setCorsHeaders(): void
  65. {
  66. $headers = [
  67. 'Access-Control-Allow-Origin' => '*',
  68. 'Access-Control-Allow-Headers' => implode(', ', self::ALLOWED_HEADERS),
  69. 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, post',
  70. 'Access-Control-Max-Age' => '1728000',
  71. 'Access-Control-Allow-Credentials' => 'true'
  72. ];
  73. foreach ($headers as $key => $value) {
  74. header("$key: $value");
  75. }
  76. }
  77. }