AutoCallManu/web.js

86 lines
2.9 KiB
JavaScript

import express from "express";
import session from "express-session";
import { deployHandler } from "./utils/handler.js";
import favicon from "serve-favicon";
async function launchWeb() {
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,
}),
);
app.use("/assets", express.static(`${process.env.WWW}/assets`));
app.use(favicon(`${process.env.WWW}/assets/images/favicon.ico`));
await deployHandler();
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,
);
});
app.get("*", async (request, response) => {
const [path, args] = parseURL(request.originalUrl);
//console.log(parseURL(request.originalUrl));
console.log(`GET: ${path}${args ? "?" + 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);
});
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];
}
export { launchWeb };