AutoCallManu/web.js

86 lines
2.9 KiB
JavaScript
Raw Normal View History

import express from "express";
import session from "express-session";
import { deployHandler } from "./utils/handler.js";
import favicon from "serve-favicon";
2023-12-06 08:46:58 +01:00
async function launchWeb() {
2023-12-06 08:46:58 +01:00
const app = express();
app.use(express.json()); // Used to parse JSON bodies
app.use(express.urlencoded({ extended: false })); //Parse URL-encoded bodies
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
}),
);
2023-12-06 08:46:58 +01:00
app.use("/assets", express.static(`${process.env.WWW}/assets`));
app.use(favicon(`${process.env.WWW}/assets/images/favicon.ico`));
2023-12-06 08:46:58 +01:00
await deployHandler();
2023-12-06 08:46:58 +01:00
app.post("*", async (request, response) => {
console.log("POST: " + request.originalUrl);
let handled = global.handler.post[request.originalUrl];
if(!handled) for(const path of Object.keys(global.handler.post)) {
if(new RegExp(path).test(request.originalUrl)) handled = global.handler.post[path];
}
if (!handled) return console.log(request.originalUrl);
if (handled.requiresLogin && !request.session.user) {
return response.redirect("/login");
}
if (handled.permissions) {
if((handled.permissions & request.session.user.permissions) == 0) return response.status(403).send("Vous n'avez pas la permission d'effectuer cette action !");
}
return await handled.execute(
request,
response,
);
2023-12-06 08:46:58 +01:00
});
app.get("*", async (request, response) => {
const [path, args] = parseURL(request.originalUrl);
const argNum = Object.keys(args).length;
console.log(`GET: ${path} ${argNum > 0 ? '('+argNum+' args)' : ""}`);
let handled = global.handler.get[path];
if(!handled) for(const path of Object.keys(global.handler.get)) {
if(new RegExp(path).test(request.originalUrl)) handled = global.handler.get[path];
}
if (!handled) return;
if (handled.requiresLogin && !request.session.user) {
return response.redirect("/login");
}
if (handled.permissions) {
if((handled.permissions & request.session.user.permissions) == 0) return response.status(403).send("Vous n'avez pas la permission d'accéder cette page !");
}
return await handled.execute(request, response, args);
2023-12-06 08:46:58 +01:00
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`App available at http://localhost:${PORT}`);
});
}
function parseURL(URL) {
const spURL = URL.split("?");
const path = spURL[0];
if(!spURL[1]) return [path, {}];
const args = {};
for (let i = 0; i < spURL[1].split("=").length; i+=2) {
const key = spURL[1].split("=")[i];
const val = spURL[1].split("=")[i+1];
args[key] = val;
}
return [path, args];
2023-12-06 08:46:58 +01:00
}
export { launchWeb };