ConnectForce/packages/server/src/main.js
2022-12-14 11:01:32 +01:00

51 lines
1.1 KiB
JavaScript

import { join } from "path";
import { fileURLToPath } from "url";
import express from "express";
import { HTTPError } from "./HTTPError.js";
const dirname = fileURLToPath(new URL(".", import.meta.url));
const app = express();
const apiKeys = [
"c4game"
];
app.use(express.static(join(dirname, "..", "..", "game", "lib", "static")));
app.use("/api", express.json());
app.use(
"/api",
(request, response, next) =>
{
const keyParam = "token";
if (keyParam in request.query)
{
let key = request.query[keyParam];
if (typeof key === "string" && apiKeys.includes(key))
{
next();
}
else
{
next(new HTTPError(401, "The specified API token is invalid"));
}
}
else
{
next(new HTTPError(401, "An API token is required"));
}
});
app.use(
[
(error, request, response, next) =>
{
response.send(`${error}`);
response.status(error instanceof HTTPError ? error.status : 500);
}
]);
app.listen(1337);