Skip to content

Commit

Permalink
BUG Fix CSP headers by using Requirements API for custom script
Browse files Browse the repository at this point in the history
  • Loading branch information
Maxime Rainville committed Feb 2, 2024
1 parent c9d8b31 commit b269844
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 24 deletions.
38 changes: 32 additions & 6 deletions src/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use SilverStripe\Core\Path;
use SilverStripe\GraphQL\Schema\Schema;
use SilverStripe\Security\SecurityToken;
use SilverStripe\View\Requirements;

class Controller extends BaseController
{
Expand All @@ -34,26 +35,51 @@ class Controller extends BaseController
public function index(HTTPRequest $request)
{
$routes = $this->getRoutes();
$json = null;
$endpoint = sizeof($routes ?? []) === 1 ? $routes[0] : null;
$csrf = SecurityToken::inst()->getValue();
$tabs = [];
if (sizeof($routes ?? []) > 1) {
$tabs = [];
foreach ($routes as $route) {
$tabs[] = [
'endpoint' => Director::absoluteURL($route),
'query' => '',
'name' => $route,
'headers' => [
'X-CSRF-TOKEN' => SecurityToken::inst()->getValue(),
'X-CSRF-TOKEN' => $csrf,
]
];
}
}

$data = [
'headers' => [
'X-CSRF-TOKEN' => $csrf,
],
'endpoint' => $endpoint,
'settings' => [
'request.globalHeaders' => [
'X-CSRF-TOKEN' => $csrf,
],
'request.credentials' => 'include',
],
];

$json = json_encode($tabs);
if ($tabs) {
$data['tabs'] = $tabs;
}

$jsonPayload = json_encode($data);

Requirements::customScript(<<<JS
window.addEventListener('load', function (event) {
GraphQLPlayground.init(document.getElementById('root'), $jsonPayload)
})
JS
);

return [
'Endpoint' => sizeof($routes ?? []) === 1 ? $routes[0] : null,
'TabsJSON' => $json,
'Endpoint' => $endpoint,
'TabsJSON' => $tabs ? json_encode($tabs): null,
];
}

Expand Down
19 changes: 1 addition & 18 deletions templates/DevTools.ss
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<title>GraphQL IDE | Silverstripe CMS</title>
<link rel="shortcut icon" href="$resourceURL('silverstripe/graphql-devtools: client/favicon.png')" />
<% require javascript('silverstripe/graphql-devtools: client/bundle.js') %>

<style>
html, body {
margin: 0;
Expand Down Expand Up @@ -91,22 +91,5 @@
<span class="title">GraphQL Playground</span>
</div>
</div>
<script>window.addEventListener('load', function (event) {
GraphQLPlayground.init(document.getElementById('root'), {
headers: {
'X-CSRF-TOKEN': '$SecurityID',
},
endpoint: '$Endpoint',
settings: {
'request.globalHeaders': {
'X-CSRF-TOKEN': '$SecurityID'
},
'request.credentials': 'include',
},
<% if $TabsJSON %>
tabs: $TabsJSON.RAW
<% end_if %>
})
})</script>
</body>
</html>

0 comments on commit b269844

Please sign in to comment.