AllowOriginMiddleware.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace app\http\middleware;
  3. use app\models\auction\Auction;
  4. use app\Request;
  5. use crmeb\interfaces\MiddlewareInterface;
  6. use think\facade\Config;
  7. use think\Response;
  8. /**
  9. * 跨域中间件
  10. * Class AllowOriginMiddleware
  11. * @package app\http\middleware
  12. */
  13. class AllowOriginMiddleware implements MiddlewareInterface
  14. {
  15. /**
  16. * header头
  17. * @var array
  18. */
  19. protected $header = [
  20. 'Access-Control-Allow-Origin' => '*',
  21. 'Access-Control-Allow-Headers' => 'Authori-zation,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
  22. 'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
  23. 'Access-Control-Max-Age' => '1728000'
  24. ];
  25. /**
  26. * 允许跨域的域名
  27. * @var string
  28. */
  29. protected $cookieDomain;
  30. /**
  31. * @param Request $request
  32. * @param \Closure $next
  33. * @return Response
  34. */
  35. public function handle(Request $request, \Closure $next)
  36. {
  37. $this->cookieDomain = Config::get('cookie.domain', '');
  38. $header = $this->header;
  39. $origin = $request->header('origin');
  40. if ($origin && ('' != $this->cookieDomain && strpos($origin, $this->cookieDomain)))
  41. $header['Access-Control-Allow-Origin'] = $origin;
  42. if ($request->method(true) == 'OPTIONS') {
  43. $response = Response::create('ok')->code(200)->header($header);
  44. } else {
  45. $response = $next($request)->header($header);
  46. }
  47. $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
  48. Auction::frequency(); // 更新场次
  49. return $response;
  50. }
  51. }