<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\middleware;


/**
 * 跨域中间件
 * 处理 CORS 请求头，允许携带凭证
 * @package app\middleware
 */
class Cors
{

    /**
     * 处理跨域请求
     * 设置CORS响应头并在OPTIONS预检时直接返回200
     * @param mixed $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $origin = $request->header('origin', '');
        if ($origin) {
            header('Access-Control-Allow-Origin: ' . $origin);
            header('Access-Control-Allow-Credentials: true');
            header('Vary: Origin');
        }

        if ($request->method() == 'OPTIONS') {
            header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS');
            header('Access-Control-Allow-Headers: Authorization, Content-Type, X-Requested-With, Token, X-Token');
            header('Access-Control-Max-Age: 86400');
            return json(['code' => 200, 'msg' => 'ok']);
        }

        header('Access-Control-Expose-Headers: Content-Disposition');
        return $next($request);
    }
}