Skip to content

Commit

Permalink
fix: Wrap in helper function and handle test envs
Browse files Browse the repository at this point in the history
  • Loading branch information
DafyddLlyr committed Jan 16, 2024
1 parent 611823f commit 71a6409
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions api.planx.uk/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { json, urlencoded } from "body-parser";
import assert from "assert";
import cookieParser from "cookie-parser";
import cookieSession from "cookie-session";
import cors from "cors";
import cors, { CorsOptions } from "cors";
import express, { ErrorRequestHandler } from "express";
import noir from "pino-noir";
import pinoLogger from "express-pino-logger";
Expand Down Expand Up @@ -38,19 +38,21 @@ useSwaggerDocs(app);

app.set("trust proxy", 1);

const CORS_ALLOWLIST = process.env.CORS_ALLOWLIST?.split(", ") || [];
const checkAllowedOrigins: CorsOptions["origin"] = (origin, callback) => {
const isProduction = process.env.APP_ENVIRONMENT === "production";
const allowList = process.env.CORS_ALLOWLIST?.split(", ") || [];
const isAllowed = origin && allowList.includes(origin);

!isProduction || isAllowed
? callback(null, true)
: callback(new Error("Not allowed by CORS"));
};

app.use(
cors({
credentials: true,
methods: "*",
origin: function (origin, callback) {
if (origin && CORS_ALLOWLIST.includes(origin)) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
origin: checkAllowedOrigins,
allowedHeaders: [
"Accept",
"Authorization",
Expand Down

0 comments on commit 71a6409

Please sign in to comment.