-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #135 from Carifio24/refactor
Refactor package to allow for more modularity
- Loading branch information
Showing
19 changed files
with
9,773 additions
and
4,157 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
import { Express } from "express"; | ||
import session from "express-session"; | ||
import bodyParser from "body-parser"; | ||
import cookieParser from "cookie-parser"; | ||
import cors, { CorsOptions } from "cors"; | ||
import { Sequelize } from "sequelize"; | ||
import sequelizeStore from "connect-session-sequelize"; | ||
import { v4 } from "uuid"; | ||
|
||
import { apiKeyMiddleware } from "./middleware"; | ||
import { ALLOWED_ORIGINS } from "./utils"; | ||
|
||
export function setupApp(app: Express, db: Sequelize) { | ||
|
||
const corsOptions: CorsOptions = { | ||
origin: "*", | ||
methods: "GET,HEAD,PUT,PATCH,POST,DELETE", | ||
preflightContinue: false, | ||
optionsSuccessStatus: 204 | ||
}; | ||
|
||
const PRODUCTION = process.env.NODE_ENV === "production"; | ||
const SESSION_MAX_AGE = 24 * 60 * 60; // in seconds | ||
|
||
app.use(cors(corsOptions)); | ||
app.use(cookieParser()); | ||
const SequelizeStore = sequelizeStore(session.Store); | ||
const store = new SequelizeStore({ | ||
db, | ||
table: "CosmicDSSession", // We need to use the model name instead of the table name (here they are different) | ||
checkExpirationInterval: 15 * 60 * 1000, // The interval at which to cleanup expired sessions in milliseconds | ||
expiration: SESSION_MAX_AGE * 1000, // The maximum age (in milliseconds) of a valid session | ||
extendDefaultFields: function (defaults, sess) { | ||
return { | ||
data: defaults.data, | ||
expires: defaults.expires, | ||
user_id: sess.user_id, | ||
username: sess.username, | ||
email: sess.email | ||
}; | ||
} | ||
}); | ||
|
||
|
||
const SECRET = "ADD_REAL_SECRET"; | ||
const SESSION_NAME = "cosmicds"; | ||
|
||
app.set("trust proxy", 1); | ||
app.use(session({ | ||
secret: SECRET, | ||
genid: (_req) => v4(), | ||
store: store, | ||
name: SESSION_NAME, | ||
saveUninitialized: false, | ||
resave: true, | ||
cookie: { | ||
path: "/", | ||
maxAge: SESSION_MAX_AGE, | ||
httpOnly: true, | ||
secure: PRODUCTION | ||
} | ||
})); | ||
store.sync(); | ||
|
||
app.use(apiKeyMiddleware); | ||
|
||
// parse requests of content-type - application/json | ||
app.use(bodyParser.json()); | ||
|
||
// parse requests of content-type - application/x-www-form-urlencoded | ||
app.use(bodyParser.urlencoded({ extended: true })); | ||
|
||
app.use(function(req, res, next) { | ||
|
||
const origin = req.get("origin"); | ||
if (origin !== undefined && ALLOWED_ORIGINS.includes(origin)) { | ||
res.header("Access-Control-Allow-Origin", origin); | ||
} | ||
next(); | ||
}); | ||
|
||
app.all("*", (req, _res, next) => { | ||
console.log(req.session.id); | ||
next(); | ||
}); | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,26 @@ | ||
import { promises } from "fs"; | ||
import { join } from "path"; | ||
import { app } from "./server"; | ||
import { createApp } from "./server"; | ||
import { getDatabaseConnection } from "./database"; | ||
|
||
const STORIES_DIR = join(__dirname, "stories"); | ||
const MAIN_FILE = "main.js"; | ||
|
||
const db = getDatabaseConnection(); | ||
const app = createApp(db); | ||
promises.readdir(STORIES_DIR, { withFileTypes: true }).then(entries => { | ||
entries.forEach(async (entry) => { | ||
if (entry.isDirectory()) { | ||
const file = join(STORIES_DIR, entry.name, MAIN_FILE); | ||
const data = await import(file); | ||
data.setup(app, db); | ||
app.use(data.path, data.router); | ||
} | ||
}); | ||
}).then(() => { | ||
import("./server"); | ||
}); | ||
|
||
|
||
// set port, listen for requests | ||
const PORT = process.env.PORT || 8081; | ||
app.listen(PORT, () => { | ||
console.log(`Server is running on port ${PORT}.`); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { Request, Response as ExpressResponse, NextFunction } from "express"; | ||
|
||
import { getAPIKey, hasPermission } from "./authorization"; | ||
import { ALLOWED_ORIGINS } from "./utils"; | ||
|
||
|
||
export async function apiKeyMiddleware(req: Request, res: ExpressResponse, next: NextFunction): Promise<void> { | ||
|
||
if (req.originalUrl === "/") { | ||
next(); | ||
return; | ||
} | ||
|
||
// The whitelisting of hosts is temporary! | ||
const host = req.headers.origin; | ||
const validOrigin = host && ALLOWED_ORIGINS.includes(host); | ||
const key = req.get("Authorization"); | ||
const apiKey = key ? await getAPIKey(key) : null; | ||
const apiKeyExists = apiKey !== null; | ||
if (validOrigin || (apiKeyExists && hasPermission(apiKey, req))) { | ||
next(); | ||
} else { | ||
res.statusCode = apiKeyExists ? 403 : 401; | ||
const message = apiKeyExists ? | ||
"Your API key does not provide permission to access this endpoint!" : | ||
"You must provide a valid CosmicDS API key!"; | ||
res.json({ message }); | ||
res.end(); | ||
} | ||
} |
Oops, something went wrong.