1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the Laravel Lodash package. |
4
|
|
|
* |
5
|
|
|
* (c) Avtandil Kikabidze aka LONGMAN <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Longman\LaravelLodash\Middlewares; |
13
|
|
|
|
14
|
|
|
use Closure; |
15
|
|
|
use Illuminate\Http\Request; |
16
|
|
|
|
17
|
|
|
class AllowCorsRequests |
18
|
|
|
{ |
19
|
|
|
public function handle(Request $request, Closure $next) |
20
|
|
|
{ |
21
|
|
|
$response = $next($request); |
22
|
|
|
|
23
|
|
|
if (! $request->headers->has('Origin')) { |
24
|
|
|
return $response; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
$host = parse_url($request->headers->get('Origin'), PHP_URL_HOST); |
28
|
|
|
if (empty($host)) { |
29
|
|
|
return $response; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$allowed_origins = config('lodash.cors.allow_origins'); |
33
|
|
|
|
34
|
|
|
$found = false; |
35
|
|
|
foreach ($allowed_origins as $origin) { |
36
|
|
|
if ($found = ends_with($host, $origin)) { |
37
|
|
|
break; |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if (! $found) { |
42
|
|
|
return $response; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if ($request->method() === 'OPTIONS') { |
46
|
|
|
$allowed_headers = config('lodash.cors.allow_headers'); |
47
|
|
|
$allowed_methods = config('lodash.cors.allow_methods'); |
48
|
|
|
|
49
|
|
|
$response |
50
|
|
|
->header('Access-Control-Allow-Origin', $request->headers->get('Origin')) |
51
|
|
|
->header('Access-Control-Allow-Credentials', 'true') |
52
|
|
|
->header('Access-Control-Allow-Methods', implode(',', $allowed_methods)) |
53
|
|
|
->header('Access-Control-Allow-Headers', implode(',', $allowed_headers)) |
54
|
|
|
->header('Access-Control-Max-Age', '1728000') |
55
|
|
|
->header('Content-Type', 'application/json'); |
56
|
|
|
} else { |
57
|
|
|
$response->headers->set('Access-Control-Allow-Credentials', 'true'); |
58
|
|
|
$response->headers->set( |
59
|
|
|
'Access-Control-Allow-Origin', |
60
|
|
|
$request->headers->get('Origin') |
61
|
|
|
); |
62
|
|
|
$response->headers->set('Content-Type', 'application/json'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $response; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|