Commit c8a1185e authored by yinxiaoling's avatar yinxiaoling

HandleCors中间件跨域

parent 7ecaf0e6
......@@ -110,4 +110,7 @@ trait Tool
curl_close($ch);
return $data;
}
}
\ No newline at end of file
......@@ -7,6 +7,7 @@ use App\Http\Controllers\Controller;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Tool;
use Maatwebsite\Excel\Facades\Excel;
//use App\Http\Requests\StrategySetCreateRequest;
class StrategySetController extends Controller
......@@ -34,14 +35,51 @@ class StrategySetController extends Controller
return $this->errorWithInfo('表单验证失败', 401);
} */
$path = $request->file('upload')->store('upload');
dd($path);
$excelReturn = $this->validUploadExcel($request,'upload',8388608); //限制最大上传文件8M
if (isset($excelReturn['code']) && $excelReturn['code'] == '401'){
return $this->errorWithInfo($excelReturn['msg'], 401);
}
dd($excelReturn);
dd('策略添加');
}
public function create()
{
dd('dddd');
public function validUploadExcel($request,$inputName,$maxUploadSize=''){
$path = storage_path()."/import/";
$path = str_replace('\\','/',$path);
$extension = $request->file($inputName)->getClientOriginalExtension();
if($extension != 'xlsx' && $extension != 'xls' ){
return ['msg'=>'非xls及xlsx格式文件', 'code'=>401];
}
if (!empty($maxUploadSize)){//限制最大上传文件(字节)
$size = $request->file($inputName)->getClientSize();
if ($size > $maxUploadSize){
return ['msg'=>'上传文件过大', 'code'=>401];
}
}
$fileName = date('YmdHis',time()).'.xlsx';
if($request->hasFile($inputName)){
if($request->file($inputName)->isValid()){
$upr = $request->file($inputName)->move($path,$fileName);
if (!$upr){
return ['msg'=>'文件上传失败', 'code'=>401];
}else{
$res = [];
Excel::load($path.'/'.$fileName,function($reader) use( &$res ){
$reader = $reader->getSheet(0);
$res = $reader->toArray();
});
$data = array_filter($res);
if (count($data) > 1001){
return ['msg'=>'条数超过1000条', 'code'=>401];
}
return $data;
}
}
}
return ['msg'=>'excel处理失败', 'code'=>401];
}
}
......@@ -19,6 +19,7 @@ class Kernel extends HttpKernel
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
];
/**
......
......@@ -4,8 +4,66 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "19201e757f42fdfb0024fe707457a34b",
"content-hash": "e3f43fbca65c9e2d68738c335cc89bdf",
"packages": [
{
"name": "asm89/stack-cors",
"version": "2.0.0",
"source": {
"type": "git",
"url": "https://github.com/asm89/stack-cors.git",
"reference": "1913589c6de3cc09de5a9bdb4f46fbd550246b40"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/asm89/stack-cors/zipball/1913589c6de3cc09de5a9bdb4f46fbd550246b40",
"reference": "1913589c6de3cc09de5a9bdb4f46fbd550246b40",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"php": "^7.0",
"symfony/http-foundation": "~2.7|~3.0|~4.0|~5.0",
"symfony/http-kernel": "~2.7|~3.0|~4.0|~5.0"
},
"require-dev": {
"phpunit/phpunit": "^6|^7|^8|^9",
"squizlabs/php_codesniffer": "^3.5"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0-dev"
}
},
"autoload": {
"psr-4": {
"Asm89\\Stack\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Alexander",
"email": "iam.asm89@gmail.com"
}
],
"description": "Cross-origin resource sharing library and stack middleware",
"homepage": "https://github.com/asm89/stack-cors",
"keywords": [
"cors",
"stack"
],
"time": "2020-04-20T10:11:31+00:00"
},
{
"name": "chumper/zipper",
"version": "v1.0.3",
......@@ -658,6 +716,82 @@
],
"time": "2020-02-22T01:51:47+00:00"
},
{
"name": "fruitcake/laravel-cors",
"version": "v2.0.0",
"source": {
"type": "git",
"url": "https://github.com/fruitcake/laravel-cors.git",
"reference": "8cc9f7e5f1b9b280ae2378b3624e6b5603e63e8c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/fruitcake/laravel-cors/zipball/8cc9f7e5f1b9b280ae2378b3624e6b5603e63e8c",
"reference": "8cc9f7e5f1b9b280ae2378b3624e6b5603e63e8c",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"asm89/stack-cors": "^2",
"illuminate/contracts": "^5.6|^6.0|^7.0|^8.0",
"illuminate/support": "^5.6|^6.0|^7.0|^8.0",
"php": ">=7.1",
"symfony/http-foundation": "^4.0|^5.0",
"symfony/http-kernel": "^4.0|^5.0"
},
"require-dev": {
"laravel/framework": "^5.5|^6.0|^7.0|^8.0",
"orchestra/dusk-updater": "^1.2",
"orchestra/testbench": "^3.5|^4.0|^5.0|^6.0",
"orchestra/testbench-dusk": "^5.1",
"phpro/grumphp": "^0.16|^0.17",
"phpunit/phpunit": "^6.0|^7.0|^8.0",
"squizlabs/php_codesniffer": "^3.5"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0-dev"
},
"laravel": {
"providers": [
"Fruitcake\\Cors\\CorsServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"Fruitcake\\Cors\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fruitcake",
"homepage": "https://fruitcake.nl"
},
{
"name": "Barry vd. Heuvel",
"email": "barryvdh@gmail.com"
}
],
"description": "Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application",
"keywords": [
"api",
"cors",
"crossdomain",
"laravel"
],
"time": "2020-05-11T09:29:18+00:00"
},
{
"name": "graham-campbell/manager",
"version": "v4.5.3",
......
on:
push:
schedule:
- cron: '0 0 * * *'
jobs:
php-tests:
runs-on: ${{ matrix.os }}
strategy:
matrix:
php: [7.4, 7.3, 7.2, 7.1, 7.0]
dependency-version: [prefer-lowest, prefer-stable]
os: [ubuntu-latest]
name: PHP${{ matrix.php }} - ${{ matrix.os }} - ${{ matrix.dependency-version }}
steps:
- name: Checkout code
uses: actions/checkout@v1
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
- name: Install dependencies
run: |
composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest
- name: Execute Unit Tests
run: vendor/bin/phpunit
- name: Check PSR-12 Codestyle
run: vendor/bin/phpcs --standard=psr12 src/
if: matrix.os == 'ubuntu-latest'
\ No newline at end of file
Copyright (c) 2013-2017 Alexander <iam.asm89@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# Stack/Cors
Library and middleware enabling cross-origin resource sharing for your
http-{foundation,kernel} using application. It attempts to implement the
[W3C Recommendation] for cross-origin resource sharing.
[W3C Recommendation]: http://www.w3.org/TR/cors/
Build status: ![.github/workflows/run-tests.yml](https://github.com/asm89/stack-cors/workflows/.github/workflows/run-tests.yml/badge.svg)
## Installation
Require `asm89/stack-cors` using composer.
## Usage
This package can be used as a library or as [stack middleware].
[stack middleware]: http://stackphp.com/
### Options
| Option | Description | Default value |
|------------------------|------------------------------------------------------------|---------------|
| allowedMethods | Matches the request method. | `array()` |
| allowedOrigins | Matches the request origin. | `array()` |
| allowedOriginsPatterns | Matches the request origin with `preg_match`. | `array()` |
| allowedHeaders | Sets the Access-Control-Allow-Headers response header. | `array()` |
| exposedHeaders | Sets the Access-Control-Expose-Headers response header. | `false` |
| maxAge | Sets the Access-Control-Max-Age response header. | `false` |
| supportsCredentials | Sets the Access-Control-Allow-Credentials header. | `false` |
The _allowedMethods_ and _allowedHeaders_ options are case-insensitive.
You don't need to provide both _allowedOrigins_ and _allowedOriginsPatterns_. If one of the strings passed matches, it is considered a valid origin.
If `array('*')` is provided to _allowedMethods_, _allowedOrigins_ or _allowedHeaders_ all methods / origins / headers are allowed.
### Example: using the library
```php
<?php
use Asm89\Stack\CorsService;
$cors = new CorsService(array(
'allowedHeaders' => array('x-allowed-header', 'x-other-allowed-header'),
'allowedMethods' => array('DELETE', 'GET', 'POST', 'PUT'),
'allowedOrigins' => array('http://localhost'),
'allowedOriginsPatterns' => array('/localhost:\d/'),
'exposedHeaders' => false,
'maxAge' => false,
'supportsCredentials' => false,
));
$cors->addActualRequestHeaders(Response $response, $origin);
$cors->handlePreflightRequest(Request $request);
$cors->isActualRequestAllowed(Request $request);
$cors->isCorsRequest(Request $request);
$cors->isPreflightRequest(Request $request);
```
## Example: using the stack middleware
```php
<?php
use Asm89\Stack\Cors;
$app = new Cors($app, array(
// you can use array('*') to allow any headers
'allowedHeaders' => array('x-allowed-header', 'x-other-allowed-header'),
// you can use array('*') to allow any methods
'allowedMethods' => array('DELETE', 'GET', 'POST', 'PUT'),
// you can use array('*') to allow requests from any origin
'allowedOrigins' => array('localhost'),
// you can enter regexes that are matched to the origin request header
'allowedOriginsPatterns' => array('/localhost:\d/'),
'exposedHeaders' => false,
'maxAge' => false,
'supportsCredentials' => false,
));
```
{
"name": "asm89/stack-cors",
"description": "Cross-origin resource sharing library and stack middleware",
"keywords": ["stack", "cors"],
"homepage": "https://github.com/asm89/stack-cors",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Alexander",
"email": "iam.asm89@gmail.com"
}
],
"require": {
"php": "^7.0",
"symfony/http-foundation": "~2.7|~3.0|~4.0|~5.0",
"symfony/http-kernel": "~2.7|~3.0|~4.0|~5.0"
},
"require-dev": {
"phpunit/phpunit": "^6|^7|^8|^9",
"squizlabs/php_codesniffer": "^3.5"
},
"autoload": {
"psr-4": {
"Asm89\\Stack\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Asm89\\Stack\\Tests\\": "tests/"
}
},
"scripts": {
"test": "phpunit",
"check-style": "phpcs -p --standard=PSR12 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src",
"fix-style": "phpcbf -p --standard=PSR12 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src"
},
"extra": {
"branch-alias": {
"dev-master": "2.0-dev"
}
}
}
<?php
/*
* This file is part of asm89/stack-cors.
*
* (c) Alexander <iam.asm89@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Asm89\Stack;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class Cors implements HttpKernelInterface
{
/**
* @var \Symfony\Component\HttpKernel\HttpKernelInterface
*/
private $app;
/**
* @var \Asm89\Stack\CorsService
*/
private $cors;
private $defaultOptions = array(
'allowedHeaders' => array(),
'allowedMethods' => array(),
'allowedOrigins' => array(),
'allowedOriginsPatterns' => array(),
'exposedHeaders' => array(),
'maxAge' => 0,
'supportsCredentials' => false,
);
public function __construct(HttpKernelInterface $app, array $options = array())
{
$this->app = $app;
$this->cors = new CorsService(array_merge($this->defaultOptions, $options));
}
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
if ($this->cors->isPreflightRequest($request)) {
$response = $this->cors->handlePreflightRequest($request);
return $this->cors->varyHeader($response, 'Access-Control-Request-Method');
}
$response = $this->app->handle($request, $type, $catch);
if ($request->getMethod() === 'OPTIONS') {
$this->cors->varyHeader($response, 'Access-Control-Request-Method');
}
return $this->cors->addActualRequestHeaders($response, $request);
}
}
<?php
/*
* This file is part of asm89/stack-cors.
*
* (c) Alexander <iam.asm89@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Asm89\Stack;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class CorsService
{
private $options;
public function __construct(array $options = array())
{
$this->options = $this->normalizeOptions($options);
}
private function normalizeOptions(array $options = array()): array
{
$options += array(
'allowedOrigins' => array(),
'allowedOriginsPatterns' => array(),
'supportsCredentials' => false,
'allowedHeaders' => array(),
'exposedHeaders' => array(),
'allowedMethods' => array(),
'maxAge' => 0,
);
// normalize array('*') to true
if (in_array('*', $options['allowedOrigins'])) {
$options['allowedOrigins'] = true;
}
if (in_array('*', $options['allowedHeaders'])) {
$options['allowedHeaders'] = true;
} else {
$options['allowedHeaders'] = array_map('strtolower', $options['allowedHeaders']);
}
if (in_array('*', $options['allowedMethods'])) {
$options['allowedMethods'] = true;
} else {
$options['allowedMethods'] = array_map('strtoupper', $options['allowedMethods']);
}
return $options;
}
/**
* @deprecated use isOriginAllowed
*/
public function isActualRequestAllowed(Request $request): bool
{
return $this->isOriginAllowed($request);
}
public function isCorsRequest(Request $request): bool
{
return $request->headers->has('Origin') && !$this->isSameHost($request);
}
public function isPreflightRequest(Request $request): bool
{
return $request->getMethod() === 'OPTIONS' && $request->headers->has('Access-Control-Request-Method');
}
public function handlePreflightRequest(Request $request): Response
{
$response = new Response();
$response->setStatusCode(204);
return $this->addPreflightRequestHeaders($response, $request);
}
public function addPreflightRequestHeaders(Response $response, Request $request): Response
{
$this->configureAllowedOrigin($response, $request);
if ($response->headers->has('Access-Control-Allow-Origin')) {
$this->configureAllowCredentials($response, $request);
$this->configureAllowedMethods($response, $request);
$this->configureAllowedHeaders($response, $request);
$this->configureMaxAge($response, $request);
}
return $response;
}
public function isOriginAllowed(Request $request): bool
{
if ($this->options['allowedOrigins'] === true) {
return true;
}
if (!$request->headers->has('Origin')) {
return false;
}
$origin = $request->headers->get('Origin');
if (in_array($origin, $this->options['allowedOrigins'])) {
return true;
}
foreach ($this->options['allowedOriginsPatterns'] as $pattern) {
if (preg_match($pattern, $origin)) {
return true;
}
}
return false;
}
public function addActualRequestHeaders(Response $response, Request $request): Response
{
$this->configureAllowedOrigin($response, $request);
if ($response->headers->has('Access-Control-Allow-Origin')) {
$this->configureAllowCredentials($response, $request);
$this->configureExposedHeaders($response, $request);
}
return $response;
}
private function configureAllowedOrigin(Response $response, Request $request)
{
if ($this->options['allowedOrigins'] === true && !$this->options['supportsCredentials']) {
// Safe+cacheable, allow everything
$response->headers->set('Access-Control-Allow-Origin', '*');
} elseif ($this->isSingleOriginAllowed()) {
// Single origins can be safely set
$response->headers->set('Access-Control-Allow-Origin', array_values($this->options['allowedOrigins'])[0]);
} else {
// For dynamic headers, check the origin first
if ($this->isOriginAllowed($request)) {
$response->headers->set('Access-Control-Allow-Origin', $request->headers->get('Origin'));
}
$this->varyHeader($response, 'Origin');
}
}
private function isSingleOriginAllowed(): bool
{
if ($this->options['allowedOrigins'] === true || !empty($this->options['allowedOriginsPatterns'])) {
return false;
}
return count($this->options['allowedOrigins']) === 1;
}
private function configureAllowedMethods(Response $response, Request $request)
{
if ($this->options['allowedMethods'] === true) {
if ($this->options['supportsCredentials']) {
$allowMethods = strtoupper($request->headers->get('Access-Control-Request-Method'));
$this->varyHeader($response, 'Access-Control-Request-Method');
} else {
$allowMethods = '*';
}
} else {
$allowMethods = implode(', ', $this->options['allowedMethods']);
}
$response->headers->set('Access-Control-Allow-Methods', $allowMethods);
}
private function configureAllowedHeaders(Response $response, Request $request)
{
if ($this->options['allowedHeaders'] === true) {
if ($this->options['supportsCredentials']) {
$allowHeaders = $request->headers->get('Access-Control-Request-Headers');
$this->varyHeader($response, 'Access-Control-Request-Headers');
} else {
$allowHeaders = '*';
}
} else {
$allowHeaders = implode(', ', $this->options['allowedHeaders']);
}
$response->headers->set('Access-Control-Allow-Headers', $allowHeaders);
}
private function configureAllowCredentials(Response $response, Request $request)
{
if ($this->options['supportsCredentials']) {
$response->headers->set('Access-Control-Allow-Credentials', 'true');
}
}
private function configureExposedHeaders(Response $response, Request $request)
{
if ($this->options['exposedHeaders']) {
$response->headers->set('Access-Control-Expose-Headers', implode(', ', $this->options['exposedHeaders']));
}
}
private function configureMaxAge(Response $response, Request $request)
{
if ($this->options['maxAge'] !== null) {
$response->headers->set('Access-Control-Max-Age', (int) $this->options['maxAge']);
}
}
public function varyHeader(Response $response, $header): Response
{
if (!$response->headers->has('Vary')) {
$response->headers->set('Vary', $header);
} elseif (!in_array($header, explode(', ', $response->headers->get('Vary')))) {
$response->headers->set('Vary', $response->headers->get('Vary') . ', ' . $header);
}
return $response;
}
private function isSameHost(Request $request): bool
{
return $request->headers->get('Origin') === $request->getSchemeAndHttpHost();
}
}
This diff is collapsed.
<?php
namespace Asm89\Stack\Tests;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class MockApp implements HttpKernelInterface
{
private $responseHeaders;
public function __construct(array $responseHeaders)
{
$this->responseHeaders = $responseHeaders;
}
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
$response = new Response();
$response->headers->add($this->responseHeaders);
return $response;
}
}
This diff is collapsed.
......@@ -12,16 +12,16 @@ return array(
'0d59ee240a4cd96ddbb4ff164fccea4d' => $vendorDir . '/symfony/polyfill-php73/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'667aeda72477189d0494fecd327c3641' => $vendorDir . '/symfony/var-dumper/Resources/functions/dump.php',
'decc78cc4436b1292c6c0d151b19445c' => $vendorDir . '/phpseclib/phpseclib/phpseclib/bootstrap.php',
'def43f6c87e4f8dfd0c9e1b1bab14fe8' => $vendorDir . '/symfony/polyfill-iconv/bootstrap.php',
'decc78cc4436b1292c6c0d151b19445c' => $vendorDir . '/phpseclib/phpseclib/phpseclib/bootstrap.php',
'2c102faa651ef8ea5874edb585946bce' => $vendorDir . '/swiftmailer/swiftmailer/lib/swift_required.php',
'bd9634f2d41831496de0d3dfe4c94881' => $vendorDir . '/symfony/polyfill-php56/bootstrap.php',
'538ca81a9a966a6716601ecf48f4eaef' => $vendorDir . '/opis/closure/functions.php',
'7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php',
'e39a8b23c42d4e1452234d762b03835a' => $vendorDir . '/ramsey/uuid/src/functions.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php',
'f0906e6318348a765ffb6eb24e0d0938' => $vendorDir . '/laravel/framework/src/Illuminate/Foundation/helpers.php',
'58571171fd5812e6e447dce228f52f4d' => $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php',
'7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php',
'3109cb1a231dcd04bee1f9f620d46975' => $vendorDir . '/paragonie/sodium_compat/autoload.php',
'6124b4c8570aa390c21fafd04a26c69f' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php',
'801c31d8ed748cfa537fa45402288c95' => $vendorDir . '/psy/psysh/src/functions.php',
......
......@@ -69,6 +69,7 @@ return array(
'Illuminate\\' => array($vendorDir . '/laravel/framework/src/Illuminate'),
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
'GrahamCampbell\\Manager\\' => array($vendorDir . '/graham-campbell/manager/src'),
'Fruitcake\\Cors\\' => array($vendorDir . '/fruitcake/laravel-cors/src'),
'Fideloper\\Proxy\\' => array($vendorDir . '/fideloper/proxy/src'),
'Faker\\' => array($vendorDir . '/fzaninotto/faker/src/Faker'),
'Enqueue\\Dsn\\' => array($vendorDir . '/enqueue/dsn'),
......@@ -85,6 +86,7 @@ return array(
'Chumper\\Zipper\\' => array($vendorDir . '/chumper/zipper/src/Chumper/Zipper'),
'BeyondCode\\DumpServer\\' => array($vendorDir . '/beyondcode/laravel-dump-server/src'),
'Barryvdh\\Debugbar\\' => array($vendorDir . '/barryvdh/laravel-debugbar/src'),
'Asm89\\Stack\\' => array($vendorDir . '/asm89/stack-cors/src'),
'App\\' => array($baseDir . '/app'),
'' => array($vendorDir . '/nesbot/carbon/src'),
);
This diff is collapsed.
[
{
"name": "asm89/stack-cors",
"version": "2.0.0",
"version_normalized": "2.0.0.0",
"source": {
"type": "git",
"url": "https://github.com/asm89/stack-cors.git",
"reference": "1913589c6de3cc09de5a9bdb4f46fbd550246b40"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/asm89/stack-cors/zipball/1913589c6de3cc09de5a9bdb4f46fbd550246b40",
"reference": "1913589c6de3cc09de5a9bdb4f46fbd550246b40",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"php": "^7.0",
"symfony/http-foundation": "~2.7|~3.0|~4.0|~5.0",
"symfony/http-kernel": "~2.7|~3.0|~4.0|~5.0"
},
"require-dev": {
"phpunit/phpunit": "^6|^7|^8|^9",
"squizlabs/php_codesniffer": "^3.5"
},
"time": "2020-04-20T10:11:31+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Asm89\\Stack\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Alexander",
"email": "iam.asm89@gmail.com"
}
],
"description": "Cross-origin resource sharing library and stack middleware",
"homepage": "https://github.com/asm89/stack-cors",
"keywords": [
"cors",
"stack"
]
},
{
"name": "barryvdh/laravel-debugbar",
"version": "v3.3.3",
......@@ -951,6 +1011,84 @@
"whoops"
]
},
{
"name": "fruitcake/laravel-cors",
"version": "v2.0.0",
"version_normalized": "2.0.0.0",
"source": {
"type": "git",
"url": "https://github.com/fruitcake/laravel-cors.git",
"reference": "8cc9f7e5f1b9b280ae2378b3624e6b5603e63e8c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/fruitcake/laravel-cors/zipball/8cc9f7e5f1b9b280ae2378b3624e6b5603e63e8c",
"reference": "8cc9f7e5f1b9b280ae2378b3624e6b5603e63e8c",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"asm89/stack-cors": "^2",
"illuminate/contracts": "^5.6|^6.0|^7.0|^8.0",
"illuminate/support": "^5.6|^6.0|^7.0|^8.0",
"php": ">=7.1",
"symfony/http-foundation": "^4.0|^5.0",
"symfony/http-kernel": "^4.0|^5.0"
},
"require-dev": {
"laravel/framework": "^5.5|^6.0|^7.0|^8.0",
"orchestra/dusk-updater": "^1.2",
"orchestra/testbench": "^3.5|^4.0|^5.0|^6.0",
"orchestra/testbench-dusk": "^5.1",
"phpro/grumphp": "^0.16|^0.17",
"phpunit/phpunit": "^6.0|^7.0|^8.0",
"squizlabs/php_codesniffer": "^3.5"
},
"time": "2020-05-11T09:29:18+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0-dev"
},
"laravel": {
"providers": [
"Fruitcake\\Cors\\CorsServiceProvider"
]
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Fruitcake\\Cors\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fruitcake",
"homepage": "https://fruitcake.nl"
},
{
"name": "Barry vd. Heuvel",
"email": "barryvdh@gmail.com"
}
],
"description": "Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application",
"keywords": [
"api",
"cors",
"crossdomain",
"laravel"
]
},
{
"name": "fzaninotto/faker",
"version": "v1.9.1",
......
# These are supported funding model platforms
github: barryvdh
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
---
name: CORS not working
about: CORS requests are blocked, follow these steeps
title: ''
labels: ''
assignees: ''
---
**Before you start**
[ ] Update to the latest version by running `composer update fruitcake/laravel-cors`
[ ] Make sure that Apache/nginx/Valet are NOT also adding CORS headers
**Check your config**
[ ] Double-check your config file with the version from the repo. Make sure the `paths` property is correctly set. Start by allowing as much as possible.
[ ] Make sure the middleware is added to the global middleware in your Http Kernel (not group)
**Clear your caches**
Please do these steps again before submitting an issue:
[ ] Clear your config cache `php artisan config:clear`, route cache (`php artisan route:clear`) and normal cache (`php artisan cache:clear`).
[ ] Make sure your permissions are setup correctly (eg. storage is writable)
**Make the request**
Open Chrome Devtools to see which requests are actually happening. Make sure you see the actual OPTIONS requests for POST/PUT/DELETE (see https://stackoverflow.com/questions/57410051/chrome-not-showing-options-requests-in-network-tab)
Please show the actual request + response headers as sent by the OPTIONS request and the POST request (when available)
on:
push:
schedule:
- cron: '0 0 * * *'
jobs:
php-tests:
runs-on: ubuntu-latest
strategy:
matrix:
php: [7.4, 7.3, 7.2]
laravel: [7.*]
testbench: [5.*]
dependency-version: [prefer-lowest, prefer-stable]
include:
- laravel: 7.*
testbench: 5.*
php: 7.4
dependency-version: prefer-stable
- laravel: 6.*
testbench: 4.*
php: 7.3
dependency-version: prefer-stable
- laravel: 5.8.*
testbench: 3.8.*
php: 7.3
dependency-version: prefer-stable
- laravel: 5.7.*
testbench: 3.7.*
php: 7.2
dependency-version: prefer-stable
- laravel: 5.6.*
testbench: 3.6.*
php: 7.1
dependency-version: prefer-stable
exclude:
- laravel: 5.7.*
php: 7.4
- laravel: 5.6.*
php: 7.4
- laravel: 5.5.*
php: 7.4
name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v1
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick
- name: Install dependencies
run: |
composer remove phpro/grumphp --no-interaction --no-update --dev
composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" "orchestra/testbench-dusk:${{ matrix.testbench }}" --no-interaction --no-update
composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest
- name: Update Dusk Chromedriver
run: vendor/bin/dusk-updater detect --auto-update
- name: Execute Unit Tests
run: vendor/bin/phpunit
- name: Upload Failed Screenshots
uses: actions/upload-artifact@v2-preview
if: failure()
with:
name: screenshots
path: tests/Browser/screenshots/*
- name: Check PSR-12 Codestyle
run: vendor/bin/phpcs --standard=psr12 src/
Copyright (c) 2013-2016 Barry vd. Heuvel
Copyright for portions of this project are held by [asm89 (Alexander)] as part of project asm89/stack-cors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\ No newline at end of file
# Change Log
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## v2.0 (2020-05-11)
[asm89/stack-cors 2.x](https://github.com/asm89/stack-cors/releases/tag/2.0.0) is now used, with these notable changes:
### Added
- CORS headers are better cachable now, with correct Vary headers (#https://github.com/asm89/stack-cors/pull/70, #https://github.com/asm89/stack-cors/pull/74)
### Changed
- CORS headers are added to non-Origin requests when possible (#https://github.com/asm89/stack-cors/pull/73)
- Requests are no longer blocked by the server, only by the browser (#https://github.com/asm89/stack-cors/pull/70)
## v1.0 (2019-12-27)
### Breaking changes
- Adding the middleware on Route groups is no longer supported. You can use the new `paths` option to match your routes
- The config file has been changed from `camelCase` to `snake_case`, please update your own config.
- The deprecated Lumen ServiceProvider has been removed.
- There is no need to manually configure the `cors` config in Lumen.
### Added
- The `paths` option is added to match certain routes only, while still using global middleware. This allows for better error handling.
## v0.11.0 (2017-12-xx)
### Breaking changes
- The wildcard matcher is changed. You can use `allowedOriginPatterns` for your own patterns,
or simple wildcards in the normal origins. Eg. `*.laravel.com` should still work.
## v0.9.0 (2016-03-2017)
### Breaking changes
- The `cors` alias is no longer added by default. Use the full class or add the alias yourself.
- The Lumen ServiceProvider has been removed. Both Laravel and Lumen should use `Barryvdh\Cors\ServiceProvider::class`.
- `Barryvdh\Cors\Stack\CorsService` moves to `\Barryvdh\Cors\CorsService` (namespace changed).
- `Barryvdh\Cors@addActualRequestHeaders` will automatically attached when Exception occured.
### Added
- Better error-handling when exceptions occur.
- A lot of tests, also on older Laravel versions.
{
"name": "fruitcake/laravel-cors",
"description": "Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application",
"keywords": ["laravel", "cors", "crossdomain", "api"],
"license": "MIT",
"authors": [
{
"name": "Fruitcake",
"homepage": "https://fruitcake.nl"
},
{
"name": "Barry vd. Heuvel",
"email": "barryvdh@gmail.com"
}
],
"require": {
"php": ">=7.1",
"illuminate/support": "^5.6|^6.0|^7.0|^8.0",
"illuminate/contracts": "^5.6|^6.0|^7.0|^8.0",
"symfony/http-foundation": "^4.0|^5.0",
"symfony/http-kernel": "^4.0|^5.0",
"asm89/stack-cors": "^2"
},
"require-dev": {
"laravel/framework": "^5.5|^6.0|^7.0|^8.0",
"phpunit/phpunit": "^6.0|^7.0|^8.0",
"orchestra/testbench": "^3.5|^4.0|^5.0|^6.0",
"squizlabs/php_codesniffer": "^3.5",
"phpro/grumphp": "^0.16|^0.17",
"orchestra/testbench-dusk": "^5.1",
"orchestra/dusk-updater": "^1.2"
},
"autoload": {
"psr-4": {
"Fruitcake\\Cors\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Fruitcake\\Cors\\Tests\\": "tests/"
}
},
"extra": {
"branch-alias": {
"dev-master": "2.0-dev"
},
"laravel": {
"providers": [
"Fruitcake\\Cors\\CorsServiceProvider"
]
}
},
"scripts": {
"test": "phpunit",
"check-style": "phpcs -p --standard=psr12 src/",
"fix-style": "phpcbf -p --standard=psr12 src/"
},
"minimum-stability": "dev",
"prefer-stable": true
}
<?php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS Options
|--------------------------------------------------------------------------
|
| The allowed_methods and allowed_headers options are case-insensitive.
|
| You don't need to provide both allowed_origins and allowed_origins_patterns.
| If one of the strings passed matches, it is considered a valid origin.
|
| If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
| all methods / origins / headers are allowed.
|
*/
/*
* You can enable CORS for 1 or multiple paths.
* Example: ['api/*']
*/
'paths' => [],
/*
* Matches the request method. `[*]` allows all methods.
*/
'allowed_methods' => ['*'],
/*
* Matches the request origin. `[*]` allows all origins. Wildcards can be used, eg `*.mydomain.com`
*/
'allowed_origins' => ['*'],
/*
* Patterns that can be used with `preg_match` to match the origin.
*/
'allowed_origins_patterns' => [],
/*
* Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
*/
'allowed_headers' => ['*'],
/*
* Sets the Access-Control-Expose-Headers response header with these headers.
*/
'exposed_headers' => [],
/*
* Sets the Access-Control-Max-Age response header when > 0.
*/
'max_age' => 0,
/*
* Sets the Access-Control-Allow-Credentials header.
*/
'supports_credentials' => false,
];
# CORS Middleware for Laravel
[![Build Status][ico-actions]][link-actions]
[![Software License][ico-license]](LICENSE.md)
[![Total Downloads][ico-downloads]][link-downloads]
Based on https://github.com/asm89/stack-cors
## About
The `laravel-cors` package allows you to send [Cross-Origin Resource Sharing](http://enable-cors.org/)
headers with Laravel middleware configuration.
If you want to have a global overview of CORS workflow, you can browse
this [image](http://www.html5rocks.com/static/images/cors_server_flowchart.png).
## Upgrading from 0.x / barryvdh-laravel-cors
When upgrading from 0.x versions, there are some breaking changes:
- **A new 'paths' property is used to enable/disable CORS on certain routes. This is empty by default, so fill it correctly!**
- **Group middleware is no longer supported, use the global middleware**
- The vendor name has changed (see installation/usage)
- The casing on the props in `cors.php` has changed from camelCase to snake_case, so if you already have a `cors.php` file you will need to update the props in there to match the new casing.
## Features
* Handles CORS pre-flight OPTIONS requests
* Adds CORS headers to your responses
* Match routes to only add CORS to certain Requests
## Installation
Require the `fruitcake/laravel-cors` package in your `composer.json` and update your dependencies:
```sh
composer require fruitcake/laravel-cors
```
## Global usage
To allow CORS for all your routes, add the `HandleCors` middleware in the `$middleware` property of `app/Http/Kernel.php` class:
```php
protected $middleware = [
// ...
\Fruitcake\Cors\HandleCors::class,
];
```
Now update the config to define the paths you want to run the CORS service on, (see Configuration below):
```php
'paths' => ['api/*'],
```
## Configuration
The defaults are set in `config/cors.php`. Publish the config to copy the file to your own config:
```sh
php artisan vendor:publish --tag="cors"
```
> **Note:** When using custom headers, like `X-Auth-Token` or `X-Requested-With`, you must set the `allowed_headers` to include those headers. You can also set it to `['*']` to allow all custom headers.
> **Note:** If you are explicitly whitelisting headers, you must include `Origin` or requests will fail to be recognized as CORS.
### Options
| Option | Description | Default value |
|--------------------------|--------------------------------------------------------------------------|---------------|
| paths | You can enable CORS for 1 or multiple paths, eg. `['api/*'] ` | `array()` |
| allowed_origins | Matches the request origin. Wildcards can be used, eg `*.mydomain.com` | `array('*')` |
| allowed_origins_patterns | Matches the request origin with `preg_match`. | `array()` |
| allowed_methods | Matches the request method. | `array('*')` |
| allowed_headers | Sets the Access-Control-Allow-Headers response header. | `array('*')` |
| exposed_headers | Sets the Access-Control-Expose-Headers response header. | `false` |
| max_age | Sets the Access-Control-Max-Age response header. | `0` |
| supports_credentials | Sets the Access-Control-Allow-Credentials header. | `false` |
`allowed_origins`, `allowed_headers` and `allowed_methods` can be set to `['*']` to accept any value.
> **Note:** Try to be a specific as possible. You can start developing with loose constraints, but it's better to be as strict as possible!
> **Note:** Because of [http method overriding](http://symfony.com/doc/current/reference/configuration/framework.html#http-method-override) in Laravel, allowing POST methods will also enable the API users to perform PUT and DELETE requests as well.
### Lumen
On Lumen, just register the ServiceProvider manually in your `bootstrap/app.php` file:
```php
$app->register(Fruitcake\Cors\CorsServiceProvider::class);
```
Also copy the [cors.php](https://github.com/fruitcake/laravel-cors/blob/master/config/cors.php) config file to `config/cors.php` and put it into action:
```php
$app->configure('cors');
```
## Global usage for Lumen
To allow CORS for all your routes, add the `HandleCors` middleware to the global middleware and set the `paths` property in the config.
```php
$app->middleware([
// ...
Fruitcake\Cors\HandleCors::class,
]);
```
### Disabling CSRF protection for your API
If possible, use a different route group with CSRF protection enabled.
Otherwise you can disable CSRF for certain requests in `App\Http\Middleware\VerifyCsrfToken`:
```php
protected $except = [
'api/*'
];
```
## License
Released under the MIT License, see [LICENSE](LICENSE).
[ico-version]: https://img.shields.io/packagist/v/fruitcake/laravel-cors.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-actions]: https://github.com/fruitcake/laravel-cors/workflows/.github/workflows/run-tests.yml/badge.svg
[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/fruitcake/laravel-cors.svg?style=flat-square
[ico-code-quality]: https://img.shields.io/scrutinizer/g/fruitcake/laravel-cors.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/fruitcake/laravel-cors.svg?style=flat-square
[link-packagist]: https://packagist.org/packages/fruitcake/laravel-cors
[link-actions]: https://github.com/fruitcake/laravel-cors/actions
[link-scrutinizer]: https://scrutinizer-ci.com/g/fruitcake/laravel-cors/code-structure
[link-code-quality]: https://scrutinizer-ci.com/g/fruitcake/laravel-cors
[link-downloads]: https://packagist.org/packages/fruitcake/laravel-cors
[link-author]: https://github.com/fruitcake
[link-contributors]: ../../contributors
<?php
namespace Fruitcake\Cors;
use Asm89\Stack\CorsService;
use Illuminate\Foundation\Application as LaravelApplication;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use Laravel\Lumen\Application as LumenApplication;
class CorsServiceProvider extends BaseServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom($this->configPath(), 'cors');
$this->app->singleton(CorsService::class, function ($app) {
$config = $app['config']->get('cors');
if ($config['exposed_headers'] && !is_array($config['exposed_headers'])) {
throw new \RuntimeException('CORS config `exposed_headers` should be `false` or an array');
}
foreach (['allowed_origins', 'allowed_origins_patterns', 'allowed_headers', 'allowed_methods'] as $key) {
if (!is_array($config[$key])) {
throw new \RuntimeException('CORS config `' . $key . '` should be an array');
}
}
// Convert case to supported options
$options = [
'supportsCredentials' => $config['supports_credentials'],
'allowedOrigins' => $config['allowed_origins'],
'allowedOriginsPatterns' => $config['allowed_origins_patterns'],
'allowedHeaders' => $config['allowed_headers'],
'allowedMethods' => $config['allowed_methods'],
'exposedHeaders' => $config['exposed_headers'],
'maxAge' => $config['max_age'],
];
// Transform wildcard pattern
foreach ($options['allowedOrigins'] as $origin) {
if (strpos($origin, '*') !== false) {
$options['allowedOriginsPatterns'][] = $this->convertWildcardToPattern($origin);
}
}
return new CorsService($options, $app);
});
}
/**
* Register the config for publishing
*
*/
public function boot()
{
if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) {
$this->publishes([$this->configPath() => config_path('cors.php')], 'cors');
} elseif ($this->app instanceof LumenApplication) {
$this->app->configure('cors');
}
}
/**
* Set the config path
*
* @return string
*/
protected function configPath()
{
return __DIR__ . '/../config/cors.php';
}
/**
* Create a pattern for a wildcard, based on Str::is() from Laravel
*
* @see https://github.com/laravel/framework/blob/5.5/src/Illuminate/Support/Str.php
* @param string $pattern
* @return string
*/
protected function convertWildcardToPattern($pattern)
{
$pattern = preg_quote($pattern, '#');
// Asterisks are translated into zero-or-more regular expression wildcards
// to make it convenient to check if the strings starts with the given
// pattern such as "library/*", making any string check convenient.
$pattern = str_replace('\*', '.*', $pattern);
return '#^' . $pattern . '\z#u';
}
}
<?php
namespace Fruitcake\Cors;
use Closure;
use Asm89\Stack\CorsService;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Http\Request;
use Illuminate\Contracts\Container\Container;
use Symfony\Component\HttpFoundation\Response;
class HandleCors
{
/** @var CorsService $cors */
protected $cors;
/** @var \Illuminate\Contracts\Container\Container $container */
protected $container;
public function __construct(CorsService $cors, Container $container)
{
$this->cors = $cors;
$this->container = $container;
}
/**
* Handle an incoming request. Based on Asm89\Stack\Cors by asm89
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return Response
*/
public function handle($request, Closure $next)
{
// Check if we're dealing with CORS and if we should handle it
if (! $this->shouldRun($request)) {
return $next($request);
}
// For Preflight, return the Preflight response
if ($this->cors->isPreflightRequest($request)) {
$response = $this->cors->handlePreflightRequest($request);
$this->cors->varyHeader($response, 'Access-Control-Request-Method');
return $response;
}
// Add the headers on the Request Handled event as fallback in case of exceptions
if (class_exists(RequestHandled::class) && $this->container->bound('events')) {
$this->container->make('events')->listen(RequestHandled::class, function (RequestHandled $event) {
$this->addHeaders($event->request, $event->response);
});
}
// Handle the request
$response = $next($request);
if ($request->getMethod() === 'OPTIONS') {
$this->cors->varyHeader($response, 'Access-Control-Request-Method');
}
return $this->addHeaders($request, $response);
}
/**
* Add the headers to the Response, if they don't exist yet.
*
* @param Request $request
* @param Response $response
* @return Response
*/
protected function addHeaders(Request $request, Response $response): Response
{
if (! $response->headers->has('Access-Control-Allow-Origin')) {
// Add the CORS headers to the Response
$response = $this->cors->addActualRequestHeaders($response, $request);
}
return $response;
}
/**
* Determine if the request has a URI that should pass through the CORS flow.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function shouldRun(Request $request): bool
{
return $this->isMatchingPath($request);
}
/**
* The the path from the config, to see if the CORS Service should run
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function isMatchingPath(Request $request): bool
{
// Get the paths from the config or the middleware
$paths = $this->container['config']->get('cors.paths', []);
foreach ($paths as $path) {
if ($path !== '/') {
$path = trim($path, '/');
}
if ($request->fullUrlIs($path) || $request->is($path)) {
return true;
}
}
return false;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment