AllowOriginMiddleware.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace app\http\middleware;
  3. use app\models\system\Site;
  4. use app\Request;
  5. use crmeb\exceptions\AuthException;
  6. use crmeb\exceptions\SiteException;
  7. use crmeb\interfaces\MiddlewareInterface;
  8. use think\facade\Config;
  9. use think\Response;
  10. /**
  11. * 跨域中间件
  12. * Class AllowOriginMiddleware
  13. * @package app\http\middleware
  14. */
  15. class AllowOriginMiddleware implements MiddlewareInterface
  16. {
  17. /**
  18. * header头
  19. * @var array
  20. */
  21. protected $header = [
  22. 'Access-Control-Allow-Origin' => '*',
  23. 'Access-Control-Allow-Headers' => 'Appid, SignTime, Sign, Authori-zation, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
  24. 'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
  25. 'Access-Control-Max-Age' => '1728000'
  26. ];
  27. /**
  28. * 允许跨域的域名
  29. * @var string
  30. */
  31. protected $cookieDomain;
  32. /**
  33. * @param Request $request
  34. * @param \Closure $next
  35. * @return Response
  36. */
  37. public function handle(Request $request, \Closure $next)
  38. {
  39. $this->cookieDomain = Config::get('cookie.domain', '');
  40. $header = $this->header;
  41. $origin = $request->header('origin');
  42. if ($origin && ('' != $this->cookieDomain && strpos($origin, $this->cookieDomain)))
  43. $header['Access-Control-Allow-Origin'] = $origin;
  44. if ($request->method(true) == 'OPTIONS') {
  45. $response = Response::create('ok')->code(200)->header($header);
  46. } else {
  47. $appid = trim(ltrim($request->header('Appid'), 'UtilLa'));
  48. $time = $request->header('SignTime');
  49. $sign = $request->header('Sign');
  50. if (!$appid || !$time || !$sign) throw new SiteException('请求异常', 400);
  51. if (!$site_id = Site::checkSign($sign, $appid, $time, $request->action())) throw new SiteException(Site::getErrorInfo('签名验证失败'), 400);
  52. Request::macro('site_id', function () use ($site_id) {
  53. return $site_id;
  54. });
  55. $response = $next($request)->header($header);
  56. }
  57. $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
  58. return $response;
  59. }
  60. }