123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- namespace app\http\middleware;
- use app\models\system\Site;
- use app\Request;
- use crmeb\exceptions\AuthException;
- use crmeb\exceptions\SiteException;
- use crmeb\interfaces\MiddlewareInterface;
- use think\facade\Config;
- use think\Response;
- /**
- * 跨域中间件
- * Class AllowOriginMiddleware
- * @package app\http\middleware
- */
- class AllowOriginMiddleware implements MiddlewareInterface
- {
- /**
- * header头
- * @var array
- */
- protected $header = [
- 'Access-Control-Allow-Origin' => '*',
- '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',
- 'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
- 'Access-Control-Max-Age' => '1728000'
- ];
- /**
- * 允许跨域的域名
- * @var string
- */
- protected $cookieDomain;
- /**
- * @param Request $request
- * @param \Closure $next
- * @return Response
- */
- public function handle(Request $request, \Closure $next)
- {
- $this->cookieDomain = Config::get('cookie.domain', '');
- $header = $this->header;
- $origin = $request->header('origin');
- if ($origin && ('' != $this->cookieDomain && strpos($origin, $this->cookieDomain)))
- $header['Access-Control-Allow-Origin'] = $origin;
- if ($request->method(true) == 'OPTIONS') {
- $response = Response::create('ok')->code(200)->header($header);
- } else {
- $appid = trim(ltrim($request->header('Appid'), 'UtilLa'));
- $time = $request->header('SignTime');
- $sign = $request->header('Sign');
- if (!$appid || !$time || !$sign) throw new SiteException('请求异常', 400);
- if (!$site_id = Site::checkSign($sign, $appid, $time, $request->action())) throw new SiteException(Site::getErrorInfo('签名验证失败'), 400);
- Request::macro('site_id', function () use ($site_id) {
- return $site_id;
- });
- $response = $next($request)->header($header);
- }
- $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
- return $response;
- }
- }
|