Skip to content

Commit

Permalink
Support allowedOrigins config option for CORS
Browse files Browse the repository at this point in the history
  • Loading branch information
dstillman committed Oct 8, 2018
1 parent ad454e0 commit 15a2961
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/cors.js
Original file line number Diff line number Diff line change
@@ -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();
};
2 changes: 2 additions & 0 deletions src/lambda.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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)));
Expand Down
2 changes: 2 additions & 0 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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)));
Expand Down

0 comments on commit 15a2961

Please sign in to comment.