From 15a29617ad7dc72ffcd44f54d80085d23dcf5b1d Mon Sep 17 00:00:00 2001 From: Dan Stillman Date: Mon, 8 Oct 2018 01:09:00 -0400 Subject: [PATCH] Support allowedOrigins config option for CORS --- src/cors.js | 17 +++++++++++++++++ src/lambda.js | 2 ++ src/server.js | 2 ++ 3 files changed, 21 insertions(+) create mode 100644 src/cors.js diff --git a/src/cors.js b/src/cors.js new file mode 100644 index 0000000..94d3e30 --- /dev/null +++ b/src/cors.js @@ -0,0 +1,17 @@ +const config = require('config'); + +module.exports = async (ctx, next) => { + if (ctx.headers.origin) { + let allowedOrigins = config.get('allowedOrigins').filter(x => x); + console.log(config.get('allowedOrigins')); + console.log(allowedOrigins); + let allAllowed = allowedOrigins.includes('*'); + if (allAllowed || allowedOrigins.includes(ctx.headers.origin)) { + ctx.set("Access-Control-Allow-Origin", allAllowed ? '*' : ctx.headers.origin); + ctx.set("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); + ctx.set("Access-Control-Allow-Headers", "Content-Type"); + ctx.set("Access-Control-Expose-Headers", "Link"); + } + } + await next(); +}; \ No newline at end of file diff --git a/src/lambda.js b/src/lambda.js index 2e14100..8fb7162 100644 --- a/src/lambda.js +++ b/src/lambda.js @@ -26,6 +26,7 @@ const Koa = require('koa'); const _ = require('koa-route'); const bodyParser = require('koa-bodyparser'); +const cors = require('./cors'); const serverless = require('serverless-http'); require('./zotero'); @@ -36,6 +37,7 @@ const WebEndpoint = require('./webEndpoint'); const ExportEndpoint = require('./exportEndpoint'); const app = module.exports = new Koa(); +app.use(cors); app.use(bodyParser({enableTypes: ['text', 'json']})); app.use(_.post('/web', WebEndpoint.handle.bind(WebEndpoint))); app.use(_.post('/search', SearchEndpoint.handle.bind(SearchEndpoint))); diff --git a/src/server.js b/src/server.js index 3baa819..d69ddcd 100644 --- a/src/server.js +++ b/src/server.js @@ -28,6 +28,7 @@ const config = require('config'); const Koa = require('koa'); const _ = require('koa-route'); const bodyParser = require('koa-bodyparser'); +const cors = require('./cors'); require('./zotero'); const Debug = require('./debug'); @@ -37,6 +38,7 @@ const WebEndpoint = require('./webEndpoint'); const ExportEndpoint = require('./exportEndpoint'); const app = module.exports = new Koa(); +app.use(cors); app.use(bodyParser({ enableTypes: ['text', 'json']})); app.use(_.post('/web', WebEndpoint.handle.bind(WebEndpoint))); app.use(_.post('/search', SearchEndpoint.handle.bind(SearchEndpoint)));