-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcors.php
More file actions
87 lines (71 loc) · 2.43 KB
/
cors.php
File metadata and controls
87 lines (71 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
namespace Grav\Plugin;
use Grav\Common\Plugin;
class CorsPlugin extends Plugin
{
/**
* @var bool
*/
protected $active = false;
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', 0]
];
}
/**
* If the URI matches a CORS route, initialize the plugin
* as active.
*/
public function onPluginsInitialized()
{
// header("Access-Control-Allow-Origin: *");
$routes = (array) $this->config->get('plugins.cors.routes');
$origins = (array) $this->config->get('plugins.cors.origins');
$methods = (array) $this->config->get('plugins.cors.methods');
$allowHeaders = (array)$this->config->get('plugins.cors.allowHeaders');
$expose = (array) $this->config->get('plugins.cors.expose');
$credentials = $this->config->get('plugins.cors.credentials');
if (!count($routes) || in_array('*', $routes)) {
$this->active = true;
}
$uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
foreach ($routes as $route) {
if ($route === '*') {
$this->active = true;
break;
}
if (@preg_match('#' . $route . '#i', $uri)) {
$this->active = true;
break;
}
}
if ($this->active) {
if (in_array('*', $origins)) {
$origin = '*';
} else {
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : false;
if (!$origin || !in_array($origin, $origins)) {
// Origin header doesn't match to the allowed origins: CORS not allowed.
return;
}
}
header("Access-Control-Allow-Origin: {$origin}");
if (count($methods)) {
header("Access-Control-Allow-Methods: " . implode(', ', $methods));
}
if (count($allowHeaders)) {
header("Access-Control-Allow-Headers: " . implode(', ', $allowHeaders));
}
if (count($expose)) {
header("Access-Control-Expose-Headers: " . implode(', ', $expose));
}
if ($credentials) {
header('Access-Control-Allow-Credentials: true');
}
}
}
}