1
0
forked from apxtri/apxtri

maj apxtri and notification registrations

This commit is contained in:
philc 2024-02-19 17:55:06 +01:00
parent c89b62befc
commit 4f1b99d494
7 changed files with 76 additions and 58 deletions

View File

@ -8,7 +8,6 @@ const cors = require("cors");
const express = require("express"); const express = require("express");
const process = require("process"); const process = require("process");
/******************************************* /*******************************************
SEE https://gitea.ndda.fr/apxtri/apxtri/wiki/Devrules SEE https://gitea.ndda.fr/apxtri/apxtri/wiki/Devrules
@ -43,8 +42,9 @@ To share configuration :
// check nginx exist // check nginx exist
if (!fs.existsSync("/etc/nginx/nginx.conf")) { if (!fs.existsSync("/etc/nginx/nginx.conf")) {
l.og( 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."); "\x1b[31m Check documentation, nginx have to be installed on this server first, no /etc/nginx/nginx.conf available, install then rerun yarn command."
);
process.exit(); process.exit();
} }
const param = {}; const param = {};
@ -54,16 +54,15 @@ argv.slice(2).forEach((arg) => {
param[kv[0]] = kv[1]; param[kv[0]] = kv[1];
} }
}); });
if (!fs.existsSync('../conf/townconf.json')){ if (!fs.existsSync("../conf/townconf.json")) {
// This is a first install // This is a first install
const nam= path.resolve('..').split('/').slice(-1)[0].split('-'); const nam = path.resolve("..").split("/").slice(-1)[0].split("-");
const town=nam[0] const town = nam[0];
const nation=nam[1] const nation = nam[1];
// doit exister param.dns pour mettre à jour le conf.json pour la conf adminapi // doit exister param.dns pour mettre à jour le conf.json pour la conf adminapi
//run setup process //run setup process
} }
// setup_xx.json is gitignore so at first install we are in dev configuration // setup_xx.json is gitignore so at first install we are in dev configuration
/* /*
let infotown = { let infotown = {
@ -114,9 +113,8 @@ if (
} }
*/ */
const conf = require(path.resolve(`../conf/townconf.json`)); const conf = require(path.resolve(`../conf/townconf.json`));
const currentmod='apxtri'; const currentmod = "apxtri";
const log = conf.api.activelog.includes(currentmod) const log = conf.api.activelog.includes(currentmod);
// Create and update ./nationchains plutot que cette fonction // Create and update ./nationchains plutot que cette fonction
// A creuser et voir comment synchro // A creuser et voir comment synchro
@ -156,7 +154,12 @@ Object.keys(tribelist).forEach((t) => {
}); });
tribeIds.push(t); tribeIds.push(t);
}); });
if (log) console.log(currentmod," Allowed DOMs to access to this apxtri server:",JSON.stringify(doms)); if (log)
console.log(
currentmod,
" Allowed DOMs to access to this apxtri server:",
JSON.stringify(doms)
);
const app = express(); const app = express();
// load express parameter from conf // load express parameter from conf
@ -168,28 +171,31 @@ app.use(bodyParser.urlencoded(conf.api.bodyparse.urlencoded));
// To set depending of post put json data size to send // To set depending of post put json data size to send
app.use(express.json()); app.use(express.json());
app.use(bodyParser.json(conf.api.bodyparse.json)); app.use(bodyParser.json(conf.api.bodyparse.json));
app.disable('x-powered-by');// for security app.disable("x-powered-by"); // for security
app.locals.tribeids = tribeIds; app.locals.tribeids = tribeIds;
if (log) console.log(currentmod," app.locals.tribeids", app.locals.tribeids); if (log) console.log(currentmod, " app.locals.tribeids", app.locals.tribeids);
// Cors management // Cors management
app.use((req,res,next)=>{ if (log) {
console.log("request origin:",req.headers.origin) app.use((req, res, next) => {
console.log(req.headers) console.log(currentmod, "request origin:", req.headers.origin);
}) console.log(currentmod, "req.headers:", req.headers);
let origlist = [undefined] next();
doms.forEach(d=>{ });
origlist.push(new RegExp(`^http.?:\/\/${d.replace(/\./g,"\\.")}`)) }
}) let origlist = [undefined];
console.log(origlist) doms.forEach((d) => {
origlist.push(new RegExp(`^http.?:\/\/${d.replace(/\./g, "\\.")}`));
});
if (log) console.log(currentmod, "List of white cors origin", origlist);
// CORS // CORS
//app.use(cors(corsOptions)); //app.use(cors(corsOptions));
app.use(cors({origin:origlist})) app.use(cors({ origin: origlist }));
// Routers add any routes from /routes and /plugins // Routers add any routes from /routes and /plugins
let logroute = "Routes available on this apxtri instance: \n"; let logroute = "Routes available on this apxtri instance: \n";
routes.forEach((r) => { routes.forEach((r) => {
try { try {
logroute += r.url.padEnd(30,' ') + r.route +"\n"; logroute += r.url.padEnd(30, " ") + r.route + "\n";
app.use(r.url, require(r.route)); app.use(r.url, require(r.route));
} catch (err) { } catch (err) {
logroute += " (err check it module.exports=router;? or ...)\n======\n "; logroute += " (err check it module.exports=router;? or ...)\n======\n ";
@ -197,10 +203,11 @@ routes.forEach((r) => {
} }
}); });
if (log) { if (log) {
console.log(currentmod,logroute) console.log(currentmod, logroute);
if (process.env.NODE_MODE=="dev") console.log( if (process.env.NODE_MODE == "dev")
`\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` 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`
);
} }
app.listen(conf.api.port, () => { app.listen(conf.api.port, () => {
@ -208,7 +215,7 @@ app.listen(conf.api.port, () => {
conf.dns.forEach((u) => { conf.dns.forEach((u) => {
webaccess += `http://${u}:${conf.api.port} `; webaccess += `http://${u}:${conf.api.port} `;
}); });
if (log) console.log(currentmod,webaccess); if (log) console.log(currentmod, webaccess);
}); });
console.log( console.log(
"\x1b[42m\x1b[37m", "\x1b[42m\x1b[37m",

View File

@ -40,10 +40,15 @@ Notifications.registertolist = (key, typekey, tribe, mlist, srckey, uuid) => {
status: 400, status: 400,
ref: "Notifications", ref: "Notifications",
msg: "formaterror", msg: "formaterror",
data: { fielderr: typekey, format: typekey }, data: { fielderr: typekey, format: typekey }
}; };
const destin = `../nationchains/tribes/${tribe}/objects/maillinglists/${typekey}_${mlist}.json`; const destin = `../nationchains/tribes/${tribe}/objects/maillinglists/${typekey}_${mlist}.json`;
console.log(destin) if (!fs.existsSync(destin)){
console.log(`######## Attention tentative d'ecriture non autorisé,le fichier n'existe pas ${destin} créer le à la main vide {}`)
return {status:406,ref:"Notifications",msg:"destinnotallow",data:{destin}}
}
const filestorage = fs.existsSync(destin) ? fs.readJsonSync(destin) : {}; const filestorage = fs.existsSync(destin) ? fs.readJsonSync(destin) : {};
//if (log) console.log(currentmod,`filestorage`,filestorage, key, (filestorage[key])); //if (log) console.log(currentmod,`filestorage`,filestorage, key, (filestorage[key]));
if (filestorage[key]) { if (filestorage[key]) {

View File

@ -181,7 +181,7 @@ Odmdb.Schema = (objectPathname, validschema, lg="en") => {
// lance requete http pour recuperer le schema avec un await axios // lance requete http pour recuperer le schema avec un await axios
} else { } else {
schemaPath = `../nationchains/tribes/${schemaPath}`; schemaPath = `../nationchains/tribes/${schemaPath}`;
console.log(path.resolve(schemaPath)) if (log) console.log(currentmod,"resolve path schemaPath:",path.resolve(schemaPath))
if (!fs.existsSync(schemaPath)) { if (!fs.existsSync(schemaPath)) {
return {}; return {};
} else { } else {

View File

@ -9,7 +9,8 @@ const Notifications = require("./Notifications.js");
const Odmdb = require("./Odmdb.js"); const Odmdb = require("./Odmdb.js");
const conf = require(`../../conf/townconf.json`); const conf = require(`../../conf/townconf.json`);
const currentmod = "Pagans";
const log = conf.api.activelog.includes(currentmod);
/** /**
* Pagan Management numeric Identity and Person (Person = Pagan Id + tribe) * Pagan Management numeric Identity and Person (Person = Pagan Id + tribe)
* *

View File

@ -7,5 +7,7 @@
"errsendsms":"Une erreur s'est produite lors de l'envoie du sms", "errsendsms":"Une erreur s'est produite lors de l'envoie du sms",
"successfullsentsms":"Sms bien envoyé à {{To}}", "successfullsentsms":"Sms bien envoyé à {{To}}",
"registersuccess":"Vous avez bien été enregistré pour être recontacté.", "registersuccess":"Vous avez bien été enregistré pour être recontacté.",
"formaterror":"Verifier vos données" "formaterror":"Verifier vos données",
"typekeyunknown":"Verifier typekey qui doit etre email ou telephone et qui est {{typeky}}",
"destinnotallow":"Check {{destin}} that not exist"
} }

View File

@ -46,14 +46,14 @@ router.get("/:alias/:tribeId", (req, res) => {
/** /**
* @api {GET} /notifications/registeranonymous/:tribe/:mlist/:typekey/:data -Contact anonymous * @api {POST} /notifications/registeranonymous/:tribe/:mlist/:typekey/:data -Contact anonymous
* @apiName register * @apiName register
* @apiGroup Notifications * @apiGroup Notifications
* @apiDescription Register an email into a mailinglist mlist * @apiDescription Register an email into a mailinglist mlist
* @apiParams {string} tribe an existing tribe * @apiBody {string} tribe an existing tribe
* @apiParams {string} mlist a mailing list name * @apiBody {string} mlist a mailing list name
* @apiParams {string} key email or phone * @apiBody {string} key email or phone
* @apiParams {string} srckey must exist in tribes/schema/lg/enumtrk_xx.json * @apiBod {string} srckey must exist in tribes/schema/lg/enumtrk_xx.json
* @apiParams {string} data the email or phone * @apiParams {string} data the email or phone
* @apiSuccess {object} update mailinglist/{mlist}.json successfull * @apiSuccess {object} update mailinglist/{mlist}.json successfull
* @apiSuccessExample {json} successfullmessage * @apiSuccessExample {json} successfullmessage
@ -61,20 +61,21 @@ router.get("/:alias/:tribeId", (req, res) => {
* {"status":200, "ref":"Notifications", "msg":"registersuccess", "data":{data, typekey, tribe, mlist, srckey, uuid}}} * {"status":200, "ref":"Notifications", "msg":"registersuccess", "data":{data, typekey, tribe, mlist, srckey, uuid}}}
* *
*/ */
router.post("/registeranonymous",checkHeaders,(req,res)=>{
router.get("/registeranonymous/:tribe/:mlist/:typekey/:srckey/:key", checkHeaders, (req, res) => { //console.log("list registration ",req.body)
console.log("pass ici") if (!req.body.typekey || !['email','telephone'].includes(req.body.typekey) ){
//Notifications.registertolist = (typekey, tribe, mlist, srckey, uuid) return res.status(406).json({status:406,ref:"Notifications",msg:"typekeyunknown",data:{typekey:req.body.typekey}})
}
result= Notifications.registertolist( result= Notifications.registertolist(
req.params.key, req.body[req.body.typekey],
req.params.typekey, req.body.typekey,
req.params.tribe, req.body.tribe,
req.params.mlist, req.body.mlist,
req.params.srckey, req.body.srckey,
req.session.header.xuuid); req.session.header.xuuid);
res.status(result.status).json(result) res.status(result.status).json(result)
}) })
/** /**
* @api {GET} /notifications/unregister/:tribe/:mlist/:typekey/:data/:validation -Contact anonymous * @api {GET} /notifications/unregister/:tribe/:mlist/:typekey/:data/:validation -Contact anonymous
* @apiName contactanonymous * @apiName contactanonymous

View File

@ -10,6 +10,8 @@ const checkHeaders = require("../middlewares/checkHeaders.js");
const isAuthenticated = require("../middlewares/isAuthenticated.js"); const isAuthenticated = require("../middlewares/isAuthenticated.js");
const conf = require(`../../conf/townconf.json`); const conf = require(`../../conf/townconf.json`);
const currentmod = "pagans";
const log = conf.api.activelog.includes(currentmod);
const router = express.Router(); const router = express.Router();
/** /**
@ -54,7 +56,7 @@ router.get("/alias/:alias", (req, res) => {
* *
*/ */
router.get("/logout", checkHeaders, isAuthenticated, (req, res) => { router.get("/logout", checkHeaders, isAuthenticated, (req, res) => {
console.log(req.session.header); if (log) console.log(currentmod,"Logout:",req.session.header);
const logout = Pagans.logout( const logout = Pagans.logout(
req.session.header.xalias, req.session.header.xalias,
req.session.header.xtribe, req.session.header.xtribe,
@ -123,7 +125,7 @@ router.get("/isauth", checkHeaders, isAuthenticated, (req, res) => {
* *
*/ */
router.post("/", checkHeaders, isAuthenticated, async (req, res) => { router.post("/", checkHeaders, isAuthenticated, async (req, res) => {
console.log('dev',`passici ${req.body}`); if (log) console.log(currentmod,"post with", req.body);
const role = { const role = {
xalias: req.session.header.xalias, xalias: req.session.header.xalias,
xprofils: req.session.header.xprofils, xprofils: req.session.header.xprofils,
@ -153,7 +155,7 @@ router.post("/", checkHeaders, isAuthenticated, async (req, res) => {
createprocess.data.email=req.body.email createprocess.data.email=req.body.email
createprocess.data.tribe=req.session.header.xtribe; createprocess.data.tribe=req.session.header.xtribe;
if (emailsent.status!=200) { if (emailsent.status!=200) {
console.log("err emailsent: ",emailsent) console.log("pagans err to send email emailsent: ",emailsent)
createprocess.data.emailerror = emailsent.data.err; createprocess.data.emailerror = emailsent.data.err;
} }
} }
@ -170,14 +172,14 @@ router.post("/", checkHeaders, isAuthenticated, async (req, res) => {
}, },
}; };
const personup = Odmdb.cud(`../nationchains/tribes/${req.body.trustedtribe}/objects/persons`, "C", persondata, {xprofils:["pagan"],xalias:req.body.alias}); const personup = Odmdb.cud(`../nationchains/tribes/${req.body.trustedtribe}/objects/persons`, "C", persondata, {xprofils:["pagan"],xalias:req.body.alias});
console.log('personup',personup) if (log) console.log(currentmod,'person create',personup)
if (personup.status==200){ if (personup.status==200){
createprocess.data.createperson=true; createprocess.data.createperson=true;
}else{ }else{
createprocess.data.createperson=false; createprocess.data.createperson=false;
createprocess.data.errorperson=true; createprocess.data.errorperson=true;
createprocess.data.errpersonup=personup.data; createprocess.data.errpersonup=personup.data;
console.log("Warning pagan created but person not created and no recovery registration", personup); if (log) console.log(currentmod,"Warning pagan created but person not created and no recovery registration", personup);
} }
res.status(createprocess.status).json(createprocess); res.status(createprocess.status).json(createprocess);
}else{ }else{