-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
WebsiteRootsConfigProvider.php
101 lines (89 loc) · 2.27 KB
/
WebsiteRootsConfigProvider.php
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
/*
* This file is part of Contao.
*
* Copyright (c) 2005-2017 Leo Feyer
*
* @license LGPL-3.0+
*/
namespace Contao\CoreBundle\Cors;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception\DriverException;
use Nelmio\CorsBundle\Options\ProviderInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Provides the configuration for the nelmio/cors-bundle.
*
* @author Yanick Witschi <https://github.com/toflar>
*/
class WebsiteRootsConfigProvider implements ProviderInterface
{
/**
* @var Connection
*/
private $connection;
/**
* Constructor.
*
* @param Connection $connection
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
/**
* {@inheritdoc}
*/
public function getOptions(Request $request)
{
if (!$this->isCorsRequest($request) || !$this->canRunDbQuery()) {
return [];
}
$stmt = $this->connection->prepare("
SELECT EXISTS (
SELECT
id
FROM
tl_page
WHERE
type = 'root' AND dns = :dns
)
");
$stmt->bindValue('dns', preg_replace('@^https?://@', '', $request->headers->get('origin')));
$stmt->execute();
if (!$stmt->fetchColumn()) {
return [];
}
return [
'allow_origin' => true,
'allow_methods' => ['HEAD', 'GET'],
'allow_headers' => ['x-requested-with'],
];
}
/**
* Checks if the request has an Origin header.
*
* @param Request $request
*
* @return bool
*/
private function isCorsRequest(Request $request)
{
return $request->headers->has('Origin')
&& $request->headers->get('Origin') !== $request->getSchemeAndHttpHost()
;
}
/**
* Checks if a database connection can be established and the table exist.
*
* @return bool
*/
private function canRunDbQuery()
{
try {
return $this->connection->isConnected() && $this->connection->getSchemaManager()->tablesExist(['tl_page']);
} catch (DriverException $e) {
return false;
}
}
}