1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Cors; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Illuminate\Http\Response; |
7
|
|
|
use Spatie\Cors\CorsProfile\CorsProfile; |
8
|
|
|
|
9
|
|
|
class Cors |
10
|
|
|
{ |
11
|
|
|
/** @var \Spatie\Cors\CorsProfile\CorsProfile */ |
12
|
|
|
protected $corsProfile; |
13
|
|
|
|
14
|
|
|
public function __construct(CorsProfile $corsProfile) |
15
|
|
|
{ |
16
|
|
|
$this->corsProfile = $corsProfile; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Handle an incoming request. |
21
|
|
|
* |
22
|
|
|
* @param \Illuminate\Http\Request $request |
23
|
|
|
* @param \Closure $next |
24
|
|
|
* @return mixed |
25
|
|
|
*/ |
26
|
|
|
public function handle($request, Closure $next) |
27
|
|
|
{ |
28
|
|
|
if (! $this->isCorsRequest($request)) { |
29
|
|
|
return $next($request); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$this->corsProfile->setRequest($request); |
33
|
|
|
|
34
|
|
|
if (! $this->corsProfile->isAllowed()) { |
35
|
|
|
return $this->forbiddenResponse(); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
if ($this->isPreflightRequest($request)) { |
39
|
|
|
return $this->handlePreflightRequest(); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$response = $next($request); |
43
|
|
|
|
44
|
|
|
return $this->corsProfile->addCorsHeaders($response); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
protected function isCorsRequest($request): bool |
48
|
|
|
{ |
49
|
|
|
if ($request->headers->has('Origin')) { |
50
|
|
|
return true; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
return $request->headers->get('Origin') !== $request->getSchemeAndHttpHost(); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
protected function isPreflightRequest($request): bool |
57
|
|
|
{ |
58
|
|
|
return $request->getMethod() === 'OPTIONS'; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
protected function handlePreflightRequest() |
62
|
|
|
{ |
63
|
|
|
if (! $this->corsProfile->isAllowed()) { |
64
|
|
|
return $this->forbiddenResponse(); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $this->corsProfile->addPreflightheaders(response('Preflight OK', 200)); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
protected function forbiddenResponse() |
71
|
|
|
{ |
72
|
|
|
return response('Forbidden.', 403); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|