Skip to content

Commit

Permalink
Fix cors
Browse files Browse the repository at this point in the history
  • Loading branch information
Timothy-Gonzalez committed Oct 13, 2024
1 parent b91640d commit 1d36c3a
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 14 deletions.
5 changes: 2 additions & 3 deletions .test.env
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
# IMPORTANT: DO NOT PUT REAL CREDENTIALS HERE!!!!

# Regex for CORS policies
PROD_REGEX=".*"
DEPLOY_REGEX=".*"
CORS_REGEX=".*"

# ----- GENERAL CREDENTIALS -----
DB_USERNAME=test-username
Expand Down Expand Up @@ -39,4 +38,4 @@ QID4 = "qid"
QID5 = "qid"
QID6 = "qid"
QID7 = "qid"
QID8 = "qid"
QID8 = "qid"
5 changes: 1 addition & 4 deletions src/common/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,7 @@ const Config = {
METADATA_URL: "https://hackillinois.github.io/adonix-metadata/config.json",

/* OAuth, Keys, & Permissions */
CORS: {
PROD_REGEX: requireEnv("PROD_REGEX"),
DEPLOY_REGEX: requireEnv("DEPLOY_REGEX"),
},
CORS_REGEX: requireEnv("CORS_REGEX"),

DB_URL: `mongodb+srv://${requireEnv("DB_USERNAME")}:${requireEnv("DB_PASSWORD")}@${requireEnv("DB_SERVER")}/main`,
DB_PARAMS: "?retryWrites=true&w=majority",
Expand Down
9 changes: 2 additions & 7 deletions src/middleware/cors-selector.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
import cors, { CorsOptions } from "cors";
import Config from "../common/config";

// Only allow a certain set of regexes to be allowed via CORS
const allowedOrigins = [new RegExp(Config.CORS.PROD_REGEX), new RegExp(Config.CORS.DEPLOY_REGEX)];

function regexPasses(target: string, patterns: RegExp[]): boolean {
return patterns.some((pattern: RegExp) => pattern.test(target));
}
const corsRegex = new RegExp(Config.CORS_REGEX);

// CORS options configuration
const corsOptions: CorsOptions = {
origin: (origin: string | undefined, callback: (error: Error | null, allow?: boolean) => void) => {
if (!origin || regexPasses(origin, allowedOrigins)) {
if (!origin || corsRegex.test(origin)) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
Expand Down

0 comments on commit 1d36c3a

Please sign in to comment.