1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Cors\CorsProfile; |
4
|
|
|
|
5
|
|
|
class DefaultProfile implements CorsProfile |
6
|
|
|
{ |
7
|
|
|
/** Illuminate\Http\Request */ |
8
|
|
|
protected $request; |
9
|
|
|
|
10
|
|
|
public function setRequest($request) |
11
|
|
|
{ |
12
|
|
|
$this->request = $request; |
13
|
|
|
} |
14
|
|
|
|
15
|
|
|
public function allowOrigins(): array |
16
|
|
|
{ |
17
|
|
|
return config('cors.default_profile.allow_origins'); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public function allowMethods(): array |
21
|
|
|
{ |
22
|
|
|
return config('cors.default_profile.allow_methods'); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function allowHeaders(): array |
26
|
|
|
{ |
27
|
|
|
return config('cors.default_profile.allow_headers'); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function maxAge(): int |
31
|
|
|
{ |
32
|
|
|
return config('cors.default_profile.max_age'); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function addCorsHeaders($response) |
36
|
|
|
{ |
37
|
|
|
return $response |
38
|
|
|
->header('Access-Control-Allow-Origin', $this->allowedOriginsToString()); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function addPreflightHeaders($response) |
42
|
|
|
{ |
43
|
|
|
return $response |
44
|
|
|
->header('Access-Control-Allow-Methods', $this->toString($this->allowMethods())) |
45
|
|
|
->header('Access-Control-Allow-Headers', $this->toString($this->allowHeaders())) |
46
|
|
|
->header('Access-Control-Allow-Origin', $this->allowedOriginsToString()) |
47
|
|
|
->header('Access-Control-Max-Age', $this->maxAge()); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function isAllowed(): bool |
51
|
|
|
{ |
52
|
|
|
if (! in_array($this->request->method(), $this->allowMethods())) { |
53
|
|
|
return false; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if (in_array('*', $this->allowOrigins())) { |
57
|
|
|
return true; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return in_array($this->request->header('Origin'), $this->allowOrigins()); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
protected function toString(array $array): string |
64
|
|
|
{ |
65
|
|
|
return implode(', ', $array); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
protected function allowedOriginsToString(): string |
69
|
|
|
{ |
70
|
|
|
if (! $this->isAllowed()) { |
71
|
|
|
return ''; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
if (in_array('*', $this->allowOrigins())) { |
75
|
|
|
return '*'; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $this->request->header('Origin'); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|