全栈小学生 05a8c49ce6 niucloud
2023-06-02 19:11:52 +08:00

71 lines
3.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
// +----------------------------------------------------------------------
// | Niucloud-admin 企业快速开发的saas管理平台
// +----------------------------------------------------------------------
// | 官方网址https://www.niucloud-admin.com
// +----------------------------------------------------------------------
// | niucloud团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: Niucloud Team
// +----------------------------------------------------------------------
namespace app\adminapi\middleware;
use app\Request;
use Closure;
use core\exception\ServerException;
/**
* http跨域请求中间件
* Class AllowCrossDomain
* @package app\adminapi\middleware
*/
class AllowCrossDomain
{
public function handle(Request $request, Closure $next)
{
$allow_header = [
system_name('admin_token_name'),
system_name('admin_site_id_name'),
system_name('channel_name'),
'lang'
];
header("Access-Control-Allow-Headers: Authorization, Sec-Fetch-Mode, DNT, X-Mx-ReqToken, Keep-Alive, User-Agent, If-Match, If-None-Match, If-Unmodified-Since, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Accept-Language, Origin, Accept-Encoding,Access-Token,version,".implode(',', $allow_header));
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, post');
header('Access-Control-Max-Age: 1728000');
header('Access-Control-Allow-Credentials:true');
//todo 周 自定义Authorization等需要在.htaccess内加上SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0 nginx同理
$allow_origin = [
rtrim(str_replace('https://','',str_replace('http://','',$request->domain())),"/"),
];
$admin_domain = env('system.admin_domain');
if(!empty($admin_domain)){
$admin_domain = explode(',', $admin_domain);
foreach($admin_domain as $v){
if(!trim($v)) continue;
$allow_origin[] = rtrim(str_replace('https://','',str_replace('http://','',$v)),"/");
}
}
// if(env('system.admin_domain')){
// $allow_origin[] = rtrim(str_replace('https://','',str_replace('http://','',env('system.admin_domain'))),"/");
// }
$referer = $request->header('referer');
$origin = '';
if(!empty($referer)){
$referer = parse_url($referer);
$referer = $referer['host'] ?? '';
$origin = rtrim(str_replace('https://','',str_replace('http://','',$referer)),"/");
}
// $origin = $request->header('origin');
if(env('app_debug') || ($origin && in_array($origin, $allow_origin))){
// header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Origin: *');
}else{
header('Access-Control-Allow-Origin: *');
throw new ServerException('SERVER_CROSS_REQUEST_FAIL', 409);
}
return $next($request);
}
}