AllowOriginMiddleware.php 1.8 KB

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