1
0
forked from apxtri/apxtri
apxtri/apxtri.js

160 lines
5.7 KiB
JavaScript
Executable File

//const { argv } = require("process");
const fs = require("fs-extra");
//const mustache = require("mustache");
const bodyParser = require("body-parser");
const glob = require("glob");
const path = require("path");
const cors = require("cors");
const express = require("express");
const process = require("process");
const Odmdb = require("./models/Odmdb.js");
/*******************************************
SEE README.md to have a quick start
********************************************/
if (!fs.existsSync("/etc/nginx/nginx.conf")) {
setupdone = false;
console.log(
"\x1b[31m Check documentation, nginx have to be installed on this server first, no /etc/nginx/nginx.conf available, install then rerun yarn command.");
}
if (!fs.existsSync("../../conf.json")) {
console.log("Warning, this is a first install you must run 'node setup.js dns=domainename user=sudoerlinux'")
process.exit();
}
const conf = require(path.resolve(`../../conf.json`));
let doms = conf.dns; // only dns of town during the init process
const currentmod = "apxtri";
const log = conf.api.activelog.includes(currentmod);
let tribelist = {};
if (fs.existsSync(`../../idx/tribeId_all.json`)) {
tribelist = fs.readJsonSync(`../../idx/tribeId_all.json`);
}
let tribeIds = Object.keys(tribelist);
// context is store in /itm/tribename.json ={contexte:{routes:[],models:[{model:,tplstringslg:[]}]}
// routes={url,route} check how to add plugin tribe route later
// keep only the 2 last part (.) of domain name to validate cors with it (generic domain)
let routes = []
tribeIds.forEach((t) => {
tribelist[t].dns.forEach((d) => {
const dm = d.split(".").slice(-2).join(".");
if (!doms.includes(dm)) doms.push(dm);
//reindex database
if (t == "smatchit" || true) {
glob.sync(`../../${t}/objects/*`).forEach(o => {
console.log(t, o)
Odmdb.runidx(o)
})
}
});
const context = {};
const pathtr = path.resolve(`../../${t}`);
context.routes = []
tribroutes = glob.sync(`${pathtr}/ap*/routes/*.js`).map(f => {
const rt = `/${t}/${path.basename(f, ".js")}`
context.routes.push(rt)
return { url: rt, route: f };
});
context.models = glob.sync(`${pathtr}/ap*/models/*.js`).map(f => {
const modname = `${path.basename(f, ".js")}`
return {
model: modname,
tplstrings: glob.sync(`${pathtr}/objects/tplstrings/${modname}_*.json`).map(l => path.basename(l, '.json').split("_")[1])
}
})
const conft = `../../itm/${t}.json`
const ctx = fs.readJsonSync(conft)
ctx.context = context
fs.outputJSONSync(conft, ctx, { spaces: 2 });
routes = routes.concat(tribroutes);
});
const app = express();
// load express parameter from conf
Object.keys(conf.api.appset).forEach((p) => {
app.set(p, conf.api.appset[p]);
});
// To set depending of data form or get size to send
app.use(bodyParser.urlencoded(conf.api.bodyparse.urlencoded));
// To set depending of post put json data size to send
app.use(express.json({ limit: '10mb', type: 'application/json', rawBody: true }));
app.use(bodyParser.json(conf.api.bodyparse.json));
app.disable("x-powered-by"); // for security
app.locals.tribeids = tribeIds;
if (log) {
console.log(
currentmod,
" Allowed DOMs to access to this apxtri server:",
JSON.stringify(doms)
);
console.log(currentmod, " app.locals.tribeids", app.locals.tribeids);
}
// Cors management
let originlst = "test";
doms.forEach((d) => {
originlst += `|${d.replace(/\./g, "\\.")}`;
});
const regtxt = `^http.?:\/\/(${originlst})`;
let cor = false;
const regorigin = new RegExp(regtxt);
app.use((req, res, next) => {
if (req.headers.origin == undefined) {
cor = true;
} else {
cor = regorigin.test(req.headers.origin);
}
if (log)
console.log(
currentmod,
"request origin:",
req.headers.origin,
"testcors:",
cor, "headers allowed: [", conf.api.exposedHeaders.join(','), "] match with reg:", regtxt
);
cors({
origin: cor,
allowedHeaders: conf.api.exposedHeaders,
exposedHeaders: conf.api.exposedHeaders,
credentials: true,
preflightContinue: false,
optionsSuccessStatus: 204
});
next();
});
// Routers add any routes from /routes and /plugins
let logroute = "Routes available on this apxtri instance: \n";
routes.forEach((r) => {
try {
logroute += r.url.padEnd(30, " ") + r.route + "\n";
app.use(r.url, require(r.route));
} catch (err) {
logroute += " (err check it module.exports=router;? or ...)\n======\n ";
console.log("raise err-:", err);
}
});
if (log) {
console.log(currentmod, logroute);
if (process.env.NODE_MODE == "dev")
console.log(
`\x1b[42m############################################################################################\x1b[0m\n\x1b[42mThis is dev conf accessible in http://dev-ants to switch this as production, you must run:\n 1 - 'yarn dev nationId:ants townId:dev dns:dev-ants' to conf your town and check it.\n 2 - 'yarn startpm2'\n Where:\n\x1b[42m * nationId have to exist in the nationchains\n * townId new or if exist must have the same current dns,\n * dns domaine that has to redirect 80/443 into this server.\n Check README's project to learn more.\x1b[0m\n To work with apxweb for the front use http://dev-ants/apxwebapp/www/websitename/src/index.html to use the api during dev process\n\x1b[42m############################################################################################\x1b[0m`
);
}
//Listen event file for each tribe
// @TODO à ajouter ici
app.listen(conf.api.port, () => {
let webaccess = `api waits request on port:${conf.api.port} for`;
conf.dns.forEach((u) => {
webaccess += `${u}/api/ `;
});
if (log) console.log(currentmod, webaccess);
});
console.log(
"\x1b[42m\x1b[37m",
"Made with love for people's freedom, enjoy !!!",
"\x1b[0m"
);