Skip to content

Commit

Permalink
Configure CORS headers #610
Browse files Browse the repository at this point in the history
  • Loading branch information
anatol-sialitski committed Oct 16, 2023
1 parent bc34407 commit 5d2e293
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 13 deletions.
48 changes: 41 additions & 7 deletions src/main/resources/api/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,6 @@ const eventLib = require('/lib/xp/event');
const graphQLApi = __.newBean('com.enonic.app.guillotine.graphql.GraphQLApi');
const syncExecutor = __.newBean('com.enonic.app.guillotine.Synchronizer');

const CORS_HEADERS = {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Origin': '*'
};

let schema;

eventLib.listener({
Expand Down Expand Up @@ -40,6 +34,46 @@ function getSchema() {
return schema;
}

function getHeaders(req) {
const config = app.config;

if (config['cors.enabled'] === 'false') {
return {};
}

const headers = {};

if (config['cors.origin']) {
headers['access-control-allow-origin'] = config['cors.origin'];
headers['vary'] = 'Origin';
} else if (req.getHeader('Origin')) {
headers['access-control-allow-origin'] = req.getHeader('Origin');
headers['vary'] = 'Origin';
} else {
headers['access-control-allow-origin'] = '*';
}

if ((config['cors.credentials'] || '') === 'true') {
headers['access-control-allow-credentials'] = 'true';
}

headers['access-control-allow-headers'] = config['cors.allowedHeaders'] || 'Content-Type';
headers['access-control-allow-methods'] = config['cors.methods'] || 'POST, OPTIONS';

if (config['cors.maxAge']) {
headers['access-control-max-age'] = config['cors.maxAge'];
}

return headers;
}

exports.options = function (req) {
return {
status: 204,
headers: getHeaders(req),
}
};

exports.get = function (req) {
return {
status: 404
Expand All @@ -51,7 +85,7 @@ exports.post = function (req) {

return {
contentType: 'application/json',
headers: CORS_HEADERS,
headers: getHeaders(req),
body: JSON.stringify(__.toNativeObject(graphQLApi.execute(getSchema(), input.query, __.toScriptValue(input.variables))))
};
}
6 changes: 0 additions & 6 deletions src/main/resources/api/api.xml

This file was deleted.

0 comments on commit 5d2e293

Please sign in to comment.