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 exposeHeaders(): array |
31
|
|
|
{ |
32
|
|
|
return config('cors.default_profile.expose_headers'); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function maxAge(): int |
36
|
|
|
{ |
37
|
|
|
return config('cors.default_profile.max_age'); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function addCorsHeaders($response) |
41
|
|
|
{ |
42
|
|
|
return $response |
43
|
|
|
->header('Access-Control-Allow-Origin', $this->allowedOriginsToString()) |
44
|
|
|
->header('Access-Control-Expose-Headers', $this->toString($this->exposeHeaders())); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function addPreflightHeaders($response) |
48
|
|
|
{ |
49
|
|
|
return $response |
50
|
|
|
->header('Access-Control-Allow-Methods', $this->toString($this->allowMethods())) |
51
|
|
|
->header('Access-Control-Allow-Headers', $this->toString($this->allowHeaders())) |
52
|
|
|
->header('Access-Control-Allow-Origin', $this->allowedOriginsToString()) |
53
|
|
|
->header('Access-Control-Max-Age', $this->maxAge()); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function isAllowed(): bool |
57
|
|
|
{ |
58
|
|
|
if (! in_array($this->request->method(), $this->allowMethods())) { |
59
|
|
|
return false; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
if (in_array('*', $this->allowOrigins())) { |
63
|
|
|
return true; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return in_array($this->request->header('Origin'), $this->allowOrigins()); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
protected function toString(array $array): string |
70
|
|
|
{ |
71
|
|
|
return implode(', ', $array); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
protected function allowedOriginsToString(): string |
75
|
|
|
{ |
76
|
|
|
if (! $this->isAllowed()) { |
77
|
|
|
return ''; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
if (in_array('*', $this->allowOrigins())) { |
81
|
|
|
return '*'; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return $this->request->header('Origin'); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|