in progress

This commit is contained in:
philc 2023-04-27 06:17:20 +02:00
parent 0c74da3b20
commit a1fa43e2bd
279 changed files with 1706 additions and 95255 deletions

1
.gitignore vendored
View File

@ -1,6 +1,7 @@
/node_modules /node_modules
/tmp /tmp
/nginx /nginx
/cleaning
/nationchains/blocks /nationchains/blocks
/nationchains/tribes /nationchains/tribes
/yarn* /yarn*

View File

@ -1,5 +1,4 @@
const path = require( 'path' ); const conf = require( '../../nationchains/tribes/conf.json' );
const config = require( '../tribes/townconf.js' );
const checkHeaders = ( req, res, next ) => { const checkHeaders = ( req, res, next ) => {
/** /**
@ -8,47 +7,48 @@ const checkHeaders = ( req, res, next ) => {
* @apiDescription Header is mandatory to access apxtrib see tribes/townconf.json.exposedHeaders * @apiDescription Header is mandatory to access apxtrib see tribes/townconf.json.exposedHeaders
* A turn around can be done with a simple get params has to be sent in the get url. Usefull to send simple get without header like ?xworkon=tribeName&xlang=en... priority is given to headers * A turn around can be done with a simple get params has to be sent in the get url. Usefull to send simple get without header like ?xworkon=tribeName&xlang=en... priority is given to headers
* For performance, tokens are store globaly in req.app.locals.tokens={xpaganid:xauth} * For performance, tokens are store globaly in req.app.locals.tokens={xpaganid:xauth}
* if xlang is not in config.languagesAvailable * if xlang is not in conf.languagesAvailable
* *
* @apiHeader {string} xauth Pagans unique jwt token store in local town Pagans data or "noauth" * @apiHeader {string} xjwt Pagans unique jwt token store in local town Pagans data or "noauth"
* @apiHeader {string} xpaganid Pagans unique Pagan id in uuid format or "nouuid" * @apiHeader {string} xpseudo Pagans unique Pagan id in uuid format or "nouuid"
* @apiHeader {string} xlang the 2 letter langage it request the api (if not exist the 2 first letter of Accept-Language header ) if lang does not exist in the town then en is set (as it always exist in en). * @apiHeader {string} xlang the 2 letter langage it request the api (if not exist the 2 first letter of Accept-Language header ) if lang does not exist in the town then en is set (as it always exist in en).
* @apiHeader {string} xtribe Tribes id where Pagan belong to * @apiHeader {string} xtribe Tribes id where pseudo want to act
* @apiHeader {string} xworkon Tribes on which pagansId want and have accessright to work on. * @apiHeader {string} xapp Name of www/xapp folder that host app that send the request
* @apiHeader {string} xapp Name of app that send the request (tribesId:websiteName) cpaganid have to have accessright on this app} * /tribeid/person/xpseudo.json have accessright on this app store in /tribe/tribeid/www/xapp
* *
* @apiError missingexposedHeaders it miss an exposedHeaders * @apiError missingexposedHeaders it miss an exposedHeaders
* *
* @apiErrorExample {json} Error-Response: * @apiErrorExample {json} Error-Response:
* HTTP/1/1 404 Not Found * HTTP/1/1 404 Not Found
* { * {
* status:404, * status:400,
* info:"|middleware|missingheaders", * ref:"middleware"
* moreinfo: xpaganid xauth * msg:"missingheaders",
* data: ["xpseudo","xjwt"]
* } * }
* *
* @apiHeaderExample {json} Header-Exemple: * @apiHeaderExample {json} Header-Exemple:
* { * {
* xtribe:"apache", * xtribe:"apache",
* xpaganid:"12123211222", * xalias:"toto",
* xworkon:"sioux", * xhash:"",
* xauth:"",
* xlang:"en", * xlang:"en",
* xapp:"" * xapp:"popular"
* } * }
*/ */
req.session = {}; req.session = {};
const header = {}; const header = {};
if (!req.header('xlang') && req.header('Content-Language')) req.params.xlang=req.header('Content-Language'); if (!req.header('xlang') && req.header('Content-Language')) req.params.xlang=req.header('Content-Language');
let missingheader = []; let missingheader = [];
for( const h of config.exposedHeaders ) { console.log('req.headers',req.headers)
for( const h of conf.api.exposedHeaders ) {
//console.log( h, req.header( h ) ) //console.log( h, req.header( h ) )
if( req.params[ h ] ) { if( req.params[ h ] ) {
header[ h ] = req.params[ h ] header[ h ] = req.params[ h ]
} else if( req.header( h ) ) { } else if( req.header( h ) ) {
header[ h ] = req.header( h ) header[ h ] = req.header( h )
} else { } else {
missingheade.push(h); missingheader.push(h);
} }
}; };
//console.log( 'header', header ) //console.log( 'header', header )
@ -59,29 +59,22 @@ const checkHeaders = ( req, res, next ) => {
// bad request // bad request
return res.status( 400 ) return res.status( 400 )
.json( { .json( {
ref:"headers" ref:"headers",
info: "missingheader", msg: "missingheader",
moreinfo: missingheader data: missingheader
} ); } );
}; };
//console.log( req.app.locals.tribeids ) //console.log( req.app.locals.tribeids )
if( !req.app.locals.tribeids.includes( header.xtribe ) ) { if( !req.app.locals.tribeids.includes( header.xtribe ) ) {
return res.status( 400 ) return res.status( 400 )
.json( { .json( {
ref:"headers" ref:"headers",
info: 'tribeiddoesnotexist', msg: 'tribeiddoesnotexist',
moreinfo: header.xtribe moreinfo: header.xtribe
} ); } );
} }
if( !req.app.locals.tribeids.includes( header.xworkon ) ) { if( !conf.api.languages.includes( header.xlang ) ) {
return res.status( 400 ) console.log('warning language requested does not exist force to en glish')
.send( {
info: [ 'workondoesnotexist' ],
ref: 'headers',
moreinfo:header.xworkon
} );
}
if( !config.languages.includes( header.xlang ) ) {
header.xlang="en"; header.xlang="en";
} }
next(); next();

View File

@ -2,7 +2,7 @@ const fs = require( 'fs-extra' );
const glob = require( 'glob' ); const glob = require( 'glob' );
const path = require( 'path' ); const path = require( 'path' );
const config = require( '../tribes/townconf.js' ); const config = require( '../../nationchains/tribes/conf.json' );
const hasAccessrighton = ( object, action, ownby ) => { const hasAccessrighton = ( object, action, ownby ) => {
/* /*

View File

@ -0,0 +1,207 @@
const jwt = require("jwt-simple");
const fs = require("fs-extra");
const moment = require("moment");
const dayjs = require("dayjs");
const glob = require("glob");
const conf = require("../../nationchains/tribes/conf.json");
const isAuthenticated = (req, res, next) => {
//once a day rm oldest tokens than 24hours
const currentday = dayjs().date();
console.log("dayjs", currentday);
console.log(
"test si menagedone" + currentday,
!fs.existsSync(`${conf.dirname}/tmp/tokensmenagedone${currentday}`)
);
if (!fs.existsSync(`${conf.dirname}/tmp/tokensmenagedone${currentday}`)) {
// clean oldest
const tsday = dayjs().date();
console.log("tsday", tsday);
glob.sync(`${conf.dirname}/tmp/tokensmenagedone*`).forEach((f) => {
fs.removeSync(f);
});
glob.sync(`${conf.dirname}/tmp/tokens/*.json`).forEach((f) => {
fs.readJson(f, (err, data) => {
if (!err && tsday - data.timestamp > 86400000) fs.remove(f);
});
});
}
//Check register in tmp/tokens/
console.log("isRegister?");
const resnotauth = {
ref: "headers",
msg: "notauthenticated",
data: {
xalias: req.session.header.xalias,
xtribe: req.session.header.xtribe,
},
};
console.lolg(req.session.header)
if (req.session.header.xalias == "anonymous") res.status(401).json(resnotauth);
const tmpfs = `${conf.dirname}/tmp/tokens/${req.session.header.xtribe}_${req.session.header.xalias}_${req.session.header.hash}.json`;
if (!fs.exists(tmpfs)) {
//check if pseudo exist as a pagan in pagans/ and as a person in xtribe/persons/ and check hash is coming from publickey
if (
!fs.existsSync(
`${conf.dirname}/nationchains/tribes/${req.session.header.xtribe}/persons/${req.session.header.xalias}.json`
)
) {
console.log(
`pseudo:${req.session.header.xalias} does not exist for xtribe ${req.session.header.xtribe}`
);
res.status(401).json(resnotauth);
}
if (
!fs.existsSync(
`${conf.dirname}/nationchains/pagans/${req.session.header.xalias}.json`
)
) {
console.log(
`pseudo:${req.session.header.xalias} does not exist as a pagan`
);
res.status(401).json(resnotauth);
}
const person = fs.readJsonSync(
`${conf.dirname}/nationchains/tribes/${req.session.header.xtribe}/persons/${req.session.header.xalias}.json`
);
const pagan = fs.readJsonSync(
`${conf.dirname}/nationchains/pagans/${req.session.header.xalias}.json`
);
//check hash with publickey pagan.publickey
// if good => create a /tmp/tokens/xtribe_xalias_xhash.json ={timestamp}
// if not good res.json(resnotauth)
}
next();
};
const isAuthenticatedold = (req, res, next) => {
/*
check if authenticated with valid token
if not => set req.session.header.xjwt=1
if yes => set for xWorkon
req.session.header.accessrights={
app:{'tribeid:website':[liste of menu]},
data:{ "sitewebsrc": "RWCDO",
"contacts": "RWCDO"}}
Liste of menu is linked with the app tht h
ave to be consistent with accessrights.data
data, list of object accessright Read Write Create Delete Owner
a xuuid can read any objet if R
if O wner means that it can only read write its object create by himself
*/
console.log("isAuthenticated()?");
//console.log( 'req.app.locals.tokens', req.app.locals.tokens )
//console.log( 'req.session.header', req.session.header );
// Check if token exist or not
req.session.header.accessrights = { app: "", data: {} };
if (
req.session.header.xalias == "1" ||
!req.app.locals.tokens[req.session.header.xalias]
) {
console.log(
`isAuthenticated no : uuid=1 (value=${req.session.header.xalias}) or locals.tokens[uuid] empty `
);
console.log(
"req.app.locals.tokens de xalias",
req.app.locals.tokens[req.session.header.xalias]
);
console.log(
"list key uuid de req.app.locals.tokens",
Object.keys(req.app.locals.tokens)
);
req.session.header.xjwt = "1";
} else if (
req.app.locals.tokens[req.session.header.xalias].TOKEN !==
req.session.header.xjwt
) {
// console.log(req.session.header.xuuid);
// console.log(req.session.header.xjwt);
// update tokens from file in case recently logged
try {
console.log(
"token not in list of token (req.app.locals.tokens) try to refresh from file"
);
req.app.locals.tokens = fs.readJsonSync(`${conf.tmp}/tokens.json`);
} catch (err) {
console.log(
`check isAuthenticated issue in reading ${conf.tmp}/tokens.json`
);
}
if (
req.app.locals.tokens[req.session.header.xalias].TOKEN !==
req.session.header.xjwt
) {
// if still does not exist then out
console.log("isAuthenticated no, token outdated");
req.session.header.xjwt = "1";
req.session.header.xalias = "1";
}
}
if (req.session.header.xjwt == "1") {
//return res.status( 403 )
return res.status(403).json({
info: ["forbiddenAccess"],
model: "Pagans",
moreinfo: "isAuthenticated faill",
});
} else {
console.log("isAuthenticated yes");
if (req.app.locals.tokens[req.session.header.xalias]) {
//console.log( `accessright pour ${req.session.header.xalias}`, req.app.locals.tokens[ req.session.header.xalias ].ACCESSRIGHTS );
//set header.accessrights from tokens.json
req.session.header.accessrights =
req.app.locals.tokens[req.session.header.xalias].ACCESSRIGHTS;
} else {
// case of bypass no accessright available
req.session.header.accessrights = {};
}
// Once per day, clean old token
const currentday = moment().date();
console.log(
"test si menagedone" + currentday,
!fs.existsSync(`${conf.tmp}/menagedone${currentday}`)
);
if (!fs.existsSync(`${conf.tmp}/menagedone${currentday}`)) {
glob.sync(`${conf.tmp}/menagedone*`).forEach((f) => {
fs.remove(f, (err) => {
if (err) {
console.log("err remove menagedone", err);
}
});
});
glob.sync(`${conf.tmp}/mdcreator*.log`).forEach((f) => {
fs.remove(f, (err) => {
if (err) {
console.log("err remove mdcreator log", err);
}
});
});
const newtokens = {};
for (const k of Object.keys(req.app.locals.tokens)) {
try {
const decodedToken = jwt.decode(
req.app.locals.tokens[k].TOKEN,
conf.jwtSecret
);
//console.log( moment( decodedToken.expiration ), moment() )
//console.log( moment( decodedToken.expiration ) >= moment() )
if (moment(decodedToken.expiration) >= moment()) {
newtokens[k] = req.app.locals.tokens[k];
}
} catch (err) {
console.log("Check isAuthenticated cleaning token ", err);
}
}
req.app.locals.tokens = newtokens;
fs.outputJsonSync(`${conf.tmp}/tokens.json`, newtokens);
fs.writeFileSync(
`${conf.tmp}/menagedone${currentday}`,
"fichier semaphore to clean data each day can be deleted with no consequence",
"utf-8"
);
}
next();
}
};
module.exports = isAuthenticated;

View File

@ -0,0 +1,7 @@
{
"missingheader":"Some header miss to have a valid request: {{#data}} {{.}} {{/data}}",
"tribeiddoesnotexist":"Header xtribe: {{data}} does not exist in this town",
"authenticated":"Your perso{{{xpseudo}}} is register for tribe {{{xtribe}}}",
"notauthenticated":"Your pseudo {{xpseudo}} are not register into tribe {{xtribe}} ",
"forbiddenAccessright":"Pagan {{data.xpseudo}} has not access right to act {{data.action}} onto object {{data.object}} for tribe {{mor.xworkon}}"
}

View File

@ -1,13 +1,9 @@
const fs = require( 'fs-extra' ); const fs = require( 'fs-extra' );
const jsonfile = require( 'jsonfile' );
const glob = require( 'glob' ); const glob = require( 'glob' );
const moment = require( 'moment' ); const moment = require( 'moment' );
const axios = require( 'axios' ); const axios = require( 'axios' );
const conf=require('../../nationchains/tribes/conf.json')
// Check if package is installed or not to pickup the right config file
const config = require( '../tribes/townconf.js' );
/* /*
Model that will process actions plan for each client like sending email campain, or anything that Model that will process actions plan for each client like sending email campain, or anything that
@ -28,7 +24,7 @@ Contracts.sendcampain = async ( param, envoicampain ) => {
} ); } );
if( retcampain.status !== 200 ) { if( retcampain.status !== 200 ) {
console.log( "err", retcampain.payload.moreinfo ); console.log( "err", retcampain.payload.moreinfo );
fs.appendFileSync( `${config.tribes}/log_erreurglobal.txt`, moment( new Date() ) fs.appendFileSync( `${conf.tribes}/log_erreurglobal.txt`, moment( new Date() )
.format( 'YYYYMMDD HH:mm:ss' ) + ' - IMPOSSIBLE TO SEND CAMPAIN TODO for :' + param.tribeid + ' -- ' + retcampain.payload.moreinfo + '\n', 'utf-8' ); .format( 'YYYYMMDD HH:mm:ss' ) + ' - IMPOSSIBLE TO SEND CAMPAIN TODO for :' + param.tribeid + ' -- ' + retcampain.payload.moreinfo + '\n', 'utf-8' );
}; };
return retcampain; return retcampain;
@ -58,10 +54,10 @@ Contracts.initActiontodo = async ( envoie ) => {
nbactionerr: 0, nbactionerr: 0,
actionlist: "" actionlist: ""
}; };
const listclient = fs.readJsonSync( `${config.tribes}/tribeids.json` ); const listclient = fs.readJsonSync( `${conf.tribes}/tribeids.json` );
for( let clid in listclient ) { for( let clid in listclient ) {
console.log( listclient[ clid ] ); console.log( listclient[ clid ] );
let listaction = glob.sync( `${config.tribes}/${listclient[clid]}/actions/todo/*.json` ); let listaction = glob.sync( `${conf.tribes}/${listclient[clid]}/actions/todo/*.json` );
for( let action in listaction ) { for( let action in listaction ) {
console.log( listaction[ action ] ) console.log( listaction[ action ] )
log.nbaction++; log.nbaction++;
@ -111,7 +107,7 @@ Contracts.initActiontodo = async ( envoie ) => {
}; };
const trace = "###################### LOGS ####################\nSTART:" + datedeb + " END:" + moment( new Date() ) const trace = "###################### LOGS ####################\nSTART:" + datedeb + " END:" + moment( new Date() )
.format( 'YYYYMMDD HH:mm:ss' ) + "\n nombre d'actions analysées : " + log.nbaction + " dont executées : " + log.nbactionexec + " dont en erreur: " + log.nbactionerr + "\n" + log.actionlist; .format( 'YYYYMMDD HH:mm:ss' ) + "\n nombre d'actions analysées : " + log.nbaction + " dont executées : " + log.nbactionexec + " dont en erreur: " + log.nbactionerr + "\n" + log.actionlist;
fs.appendFileSync( `${config.tribes}/log.txt`, trace, 'utf-8' ); fs.appendFileSync( `${conf.tribes}/log.txt`, trace, 'utf-8' );
return "done"; return "done";
} }
module.exports = Contracts; module.exports = Contracts;

View File

@ -4,7 +4,7 @@ const glob = require("glob");
const jwt = require("jwt-simple"); const jwt = require("jwt-simple");
const axios = require("axios"); const axios = require("axios");
const path=require('path'); const path=require('path');
//const config = require("../tribes/townconf.js"); const conf=require('../../nationchains/tribes/conf.json')
const Odmdb = require('./Odmdb.js'); const Odmdb = require('./Odmdb.js');
// lowercase 1st letter is normal // lowercase 1st letter is normal
const towns = require('./Towns.js'); const towns = require('./Towns.js');
@ -28,24 +28,24 @@ Nations.updateChains = async (newtown) =>{
* @newtown {object} optional to request a registration in the nationchain network * @newtown {object} optional to request a registration in the nationchain network
* if newtown exist then it send a request to update itself else it just refresh from existing town. * if newtown exist then it send a request to update itself else it just refresh from existing town.
* Check public nationchains are up to date from the existing list of towns * Check public nationchains are up to date from the existing list of towns
* Each object to sync have a /index/config.json with key lastupdate = timestamp last update * Each object to sync have a /idx/conf.json with key lastupdate = timestamp last update
* tribes is not synchonized and contain private information * tribes is not synchonized and contain private information
* A town is a network node of the nationchains and allow to synchronize new * A town is a network node of the nationchains and allow to synchronize new
*/ */
const res= {status:400}; const res= {status:400};
const ref2update={} const ref2update={}
glob.sync('nationchains/**/index/config.json').forEach(f=>{ glob.sync('nationchains/**/idx/conf.json').forEach(f=>{
const ref=fs.readJsonSync(f) const ref=fs.readJsonSync(f)
ref2update[path.basename(ref.schema,'.json')]=ref.lastupdate; ref2update[path.basename(ref.schema,'.json')]=ref.lastupdate;
}) })
console.log(ref2update) console.log(ref2update)
// Get list of town to check n of them have fresh update // Get list of town to check n of them have fresh update
const knowntowns =fs.readJsonSync('nationchains/towns/index/towns_townId_all.json'); const knowntowns =fs.readJsonSync('nationchains/towns/idx/towns_townId_all.json');
let promiselistblock=[] let promiselistblock=[]
let towidlist=[] let towidlist=[]
Object.keys(knowntowns).forEach(townid=>{ Object.keys(knowntowns).forEach(townid=>{
// identify the town with the highest block to update town // identify the town with the highest block to update town
promiselistblock.push(axios.get(`${knowntowns[townid].url}/blocks/index/config.json`)); promiselistblock.push(axios.get(`${knowntowns[townid].url}/blocks/idx/conf.json`));
townidlistblock.push(townid) townidlistblock.push(townid)
}); });
let selectedtown="" let selectedtown=""
@ -64,7 +64,7 @@ Nations.updateChains = async (newtown) =>{
}) })
let promiselistref=[] let promiselistref=[]
Object.keys(ref2update).forEach(ob=>{ Object.keys(ref2update).forEach(ob=>{
promiselistref.push(axios.get(`${knowntowns[selectedtown].url}/${obj}/index/config.json`)); promiselistref.push(axios.get(`${knowntowns[selectedtown].url}/${obj}/idx/conf.json`));
}) })
await Promise.all(promiselistref) await Promise.all(promiselistref)
.then(rep=>{ .then(rep=>{
@ -78,7 +78,7 @@ Nations.updateChains = async (newtown) =>{
return res return res
} }
Nation.update=(nationsource)=>{ Nations.update=(nationsource)=>{
/** /**
* Update object nation with last update * Update object nation with last update
*/ */
@ -108,21 +108,21 @@ Nations.synchronize = () => {
let currentinstance = initcurrentinstance; let currentinstance = initcurrentinstance;
try { try {
currentinstance = fs.readFileSync( currentinstance = fs.readFileSync(
`${config.tribes}/${config.mayorId}/nationchains/nodes/${config.rootURL}`, `${conf.tribes}/${conf.mayorId}/nationchains/nodes/${conf.rootURL}`,
"utf-8" "utf-8"
); );
} catch (err) { } catch (err) {
console.log("first init"); console.log("first init");
} }
const loginsglob = fs.readJsonSync(`${config.tmp}/loginsglob.json`, "utf-8"); const loginsglob = fs.readJsonSync(`${conf.tmp}/loginsglob.json`, "utf-8");
currentinstance.logins = Object.keys(loginsglob); currentinstance.logins = Object.keys(loginsglob);
currentinstance.tribeids = [...new Set(Object.values(loginsglob))]; currentinstance.tribeids = [...new Set(Object.values(loginsglob))];
currentinstance.instanceknown = glob.Sync( currentinstance.instanceknown = glob.Sync(
`${config.tribes}/${config.mayorId}/nationchains/nodes/*` `${conf.tribes}/${conf.mayorId}/nationchains/nodes/*`
); );
//Save it //Save it
fs.outputJsonSync( fs.outputJsonSync(
`${config.tribes}/${config.mayorId}/nationchains/nodes/${config.rootURL}`, `${conf.tribes}/${conf.mayorId}/nationchains/nodes/${conf.rootURL}`,
currentinstance currentinstance
); );
// proof of work // proof of work
@ -130,7 +130,7 @@ Nations.synchronize = () => {
// if find then send to all for update and try to get token // if find then send to all for update and try to get token
// in any case rerun Nations.synchronize() // in any case rerun Nations.synchronize()
currentinstance.instanceknown.forEach((u) => { currentinstance.instanceknown.forEach((u) => {
if (u != config.rootURL) { if (u != conf.rootURL) {
//send currentinstance info and get back state of //send currentinstance info and get back state of
axios axios
.post(`https://${u}/nationchains/push`, currentinstance) .post(`https://${u}/nationchains/push`, currentinstance)
@ -138,7 +138,7 @@ Nations.synchronize = () => {
newdata = rep.payload.moreinfo; newdata = rep.payload.moreinfo;
//Available update info //Available update info
fs.readJson( fs.readJson(
`${config.tribes}/${config.mayorId}/nationchains/nodes/${u}`, `${conf.tribes}/${conf.mayorId}/nationchains/nodes/${u}`,
(err, data) => { (err, data) => {
if (err) { if (err) {
data.negatifupdate += 1; data.negatifupdate += 1;
@ -155,7 +155,7 @@ Nations.synchronize = () => {
//init the domain for next update //init the domain for next update
initcurrentinstance.firsttimeupdate = Date.now(); initcurrentinstance.firsttimeupdate = Date.now();
fs.outputJson( fs.outputJson(
`${config.tribes}/${config.mayorId}/nationchains/nodes/${k}`, `${conf.tribes}/${conf.mayorId}/nationchains/nodes/${k}`,
initcurrentinstance, initcurrentinstance,
"utf-8" "utf-8"
); );
@ -164,7 +164,7 @@ Nations.synchronize = () => {
} }
//save with info //save with info
fs.outputJson( fs.outputJson(
`${config.tribes}/${config.mayorId}/nationchains/nodes/${u}`, `${conf.tribes}/${conf.mayorId}/nationchains/nodes/${u}`,
data data
); );
} }
@ -175,7 +175,7 @@ Nations.synchronize = () => {
data.negatifupdate += 1; data.negatifupdate += 1;
data.lasttimeupdate = Date.now(); data.lasttimeupdate = Date.now();
fs.outputJson( fs.outputJson(
`${config.tribes}/${config.mayorId}/nationchains/nodes/${u}`, `${conf.tribes}/${conf.mayorId}/nationchains/nodes/${u}`,
data data
); );
}); });
@ -223,4 +223,4 @@ Nations.create = (conf) => {
return res return res
}; };
module.exports = Nationchains; module.exports = Nations;

View File

@ -2,7 +2,7 @@ const glob = require("glob");
const path = require("path"); const path = require("path");
const fs = require("fs-extra"); const fs = require("fs-extra");
const axios = require('axios'); const axios = require('axios');
//const config = require( '../tribes/townconf.js' ); const conf=require('../../nationchains/tribes/conf.json')
const Checkjson = require(`./Checkjson.js`); const Checkjson = require(`./Checkjson.js`);
/* This manage Objects for indexing and check and act to CRUD /* This manage Objects for indexing and check and act to CRUD
@ -21,21 +21,22 @@ Input: metaobject => data mapper of Key: Value
*/ */
Odmdb.setObject=(schemaPath, objectPath, objectName, schema, lgjson, lg)=>{ Odmdb.setObject=(schemaPath, objectPath, objectName, schema, lgjson, lg)=>{
/* /**
@schemapath {string} path to create or replace a schema ${schemaPath}/schema/ *
@objectPath {string} path where object are store * @schemapath {string} path to create or replace a schema ${schemaPath}/schema/
@objectName {string} name of the object * @objectPath {string} path where object are store
@schema {object} the json schema for this object * @objectName {string} name of the object
@lgjson {object} the json file for a specific language * @schema {object} the json schema for this object
@lg {string} the 2 letters language * @lgjson {object} the json file for a specific language
* @lg {string} the 2 letters language
a shema : *
schemaPath/schema/objectName.json * a shema :
/lg/objectName_{lg}.json * schemaPath/schema/objectName.json
an object : * /lg/objectName_{lg}.json
objectPath/objectName/index/config.json ={"schema":"relativpathfile or http"} * an object :
/uniqueid.json defining schema * objectPath/objectName/idx/confjson ={"schema":"relativpathfile or http"}
* /uniqueid.json defining schema
*
*/ */
if (!fs.existsSync(schemaPath)){ if (!fs.existsSync(schemaPath)){
return {status:404, ref:"Odmdb", info:"pathnamedoesnotexist", moreinfo:{fullpath:schemaPath}} return {status:404, ref:"Odmdb", info:"pathnamedoesnotexist", moreinfo:{fullpath:schemaPath}}
@ -52,7 +53,7 @@ Odmdb.setObject=(schemaPath, objectPath, objectName, schema, lgjson, lg)=>{
} }
//create environnement object with the new schema config //create environnement object with the new schema config
if (!fs.existsSync(`${objectPath}/${objectName}`)){ if (!fs.existsSync(`${objectPath}/${objectName}`)){
fs.outputJsonSync(`${objectPath}/${objectName}/index/config.json`,{schema:`${schemaPath}/schema/${objectName}.json`},{spaces:2}) fs.outputJsonSync(`${objectPath}/${objectName}/idx/confjson`,{schema:`${schemaPath}/schema/${objectName}.json`},{spaces:2})
} }
return {status:200} return {status:200}
} }
@ -136,7 +137,7 @@ Odmdb.Checkjson = (objectPath, objectName, data, withschemacheck) => {
*/ */
const res = { status: 200 }; const res = { status: 200 };
//get schema link of object //get schema link of object
const schemaPath = fs.readJsonSync(`${objectPath}/${objectName}/index/config.json`)['schema'] const schemaPath = fs.readJsonSync(`${objectPath}/${objectName}/idx/confjson`)['schema']
if (schemaPath.substring(0,4)=="http"){ if (schemaPath.substring(0,4)=="http"){
// lance requete http pour recuperer le schema // lance requete http pour recuperer le schema
}else{ }else{

120
api/models/Pagans.js Normal file
View File

@ -0,0 +1,120 @@
const glob = require("glob");
const path = require("path");
const fs = require("fs-extra");
const axios = require('axios');
const openpgp = require('openpgp');
const conf=require('../../nationchains/tribes/conf.json')
/**
* Pagan Management numeric Identity
*
*
*
*/
const Pagans= {}
Pagans.createId = async (alias,passphrase) =>{
/**
* @param {string} alias a unique alias that identify an identity
* @param {string} passphrase a string to cipher the publicKey (can be empty, less secure but simpler)
* @return {publicKey,privateKey} with userIds = [{alias}]
*/
let apxpagans={};
if (fs.existsSync(`${conf.dirname}/nationchains/pagans/idx/alias_all.json`)){
apxpagans = fs.readJsonSync(
`${conf.dirname}/nationchains/pagans/idx/alias_all.json`
);
}
if (Object.keys(apxpagans).includes(alias)){
return {status:409,ref:"pagans",msg:"aliasalreadyexist"}
};
const {privateKey,publicKey} = await openpgp.generateKey({
type: "ecc", // Type of the key, defaults to ECC
curve: "curve25519", // ECC curve name, defaults to curve25519
userIDs: [{ alias: alias }], // you can pass multiple user IDs
passphrase: passphrase, // protects the private key
format: "armored", // output key format, defaults to 'armored' (other options: 'binary' or 'object')
});
console.log(privateKey)
console.log(publicKey)
apxpagans[alias]={alias,publicKey};
fs.outputJsonSync(`${conf.dirname}/nationchains/pagans/idx/alias_all.json`,apxpagans);
fs.outputJsonSync(`${conf.dirname}/nationchains/pagans/itm/${alias}.json`,{alias,publicKey});
return {status:200, data:{alias,privateKey,publicKey}}
}
Pagans.generateKey = async (alias, passphrase) => {
/**
* @param {string} alias a unique alias that identify an identity
* @param {string} passphrase a string to cipher the publicKey (can be empty, less secure but simpler)
* @return {publicKey,privateKey} with userIds = [{alias}]
*/
const { privateKey, publicKey } = await openpgp.generateKey({
type: "ecc", // Type of the key, defaults to ECC
curve: "curve25519", // ECC curve name, defaults to curve25519
userIDs: [{ alias: alias }], // you can pass multiple user IDs
passphrase: passphrase, // protects the private key
format: "armored", // output key format, defaults to 'armored' (other options: 'binary' or 'object')
});
// key start by '-----BEGIN PGP PRIVATE KEY BLOCK ... '
// get liste of alias:pubklickey await axios.get('api/v0/pagans')
// check alias does not exist
console.log(privateKey)
return { alias, privateKey, publicKey };
};
//console.log( Pagans.generateKey('toto',''))
Pagans.detachedSignature = async (pubK, privK, passphrase, message) => {
/**
* @pubK {string} a text public key
* @privK {string} a test priv key
* @passphrase {string} used to read privK
* @message {string} message to sign
* @Return a detached Signature of the message
*/
const publicKey = await openpgp.readKey({ armoredKey: pubK });
const privateKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: privK }),
passphrase,
});
const msg = await openpgp.createMessage({ text: message });
return await openpgp.sign({ msg, signinKeys: privK, detached: true });
};
Pagans.checkdetachedSignature = async (
alias,
pubK,
detachedSignature,
message
) => {
/**
* @alias {string} alias link to the publicKey
* @pubK {string} publiKey text format
* @detachedSignature {string} a detachedsignatured get from apx.detachedSignature
* @message {string} the message signed
* @return {boolean} true the message was signed by alias
* false the message was not signed by alias
*/
const publicKey = await openpgp.readKey({ armoredKey: pubK });
const msg = await openpgp.createMessage({ text: message });
const signature = await openpgp.readSignature({
armoredSignature: detachedSignature, // parse detached signature
});
const verificationResult = await openpgp.verify({
msg, // Message object
signature,
verificationKeys: publicKey,
});
const { verified, keyID } = verificationResult.signatures[0];
try {
await verified; // throws on invalid signature
console.log("Signed by key id " + keyID.toHex());
return KeyId.toHex().alias == alias;
} catch (e) {
console.log("Signature could not be verified: " + e.message);
return false;
}
};
module.exports=Pagans;

View File

@ -3,6 +3,7 @@ const path = require("path");
const dnsSync = require("dns-sync"); const dnsSync = require("dns-sync");
const mustache = require("mustache"); const mustache = require("mustache");
const readlineSync = require("readline-sync"); const readlineSync = require("readline-sync");
/** /**
* This Setup is run at the first installation * This Setup is run at the first installation
* This is not an exportable module * This is not an exportable module
@ -27,7 +28,7 @@ Setup.check = () => {
); );
process.exit(); process.exit();
} }
if (fs.existsSync("./nationchains/tribes/index/conf.json")) { if (fs.existsSync("./nationchains/tribes/conf.json")) {
console.log( console.log(
"\x1b[31m Be carefull you already have a town set in ./nationchains/tribes/index.conf.json, check and remove it if you want to setup this town." "\x1b[31m Be carefull you already have a town set in ./nationchains/tribes/index.conf.json, check and remove it if you want to setup this town."
); );
@ -36,29 +37,66 @@ Setup.check = () => {
return true; return true;
}; };
Setup.init = () => { Setup.init = async () => {
// Get standard conf and current data // Get standard conf and current data
const townconf = fs.readJsonSync("./nationchains/www/adminapx/townconf.json"); const townconf = fs.readJsonSync("./nationchains/www/adminapx/townconf.json");
const apxnations = fs.readJsonSync(
`./nationchains/nations/idx/nationId_all.json`
);
const apxtowns = fs.readJsonSync(`./nationchains/towns/idx/townId_all.json`);
let apxpagans={}
if (fs.existsSync(`./nationchains/pagans/idx/alias_all.json`)){
apxpagans = fs.readJsonSync(
`./nationchains/pagans/idx/alias_all.json`
);
}
if (!Object.keys(apxnations).includes(townconf.nationId)) {
console.log(
`Sorry nationId ${townconf.nationId} does not exist, please change with an existing nation `
);
process.exit();
}
if (Object.keys(apxtowns).includes(townconf.townId)) {
console.log(
`Sorry townId ${townconf.townId} already exist, please change it`
);
process.exit();
}
/*
if (Object.keys(apxpagans).includes(townconf.mayorId)) {
console.log(
`Sorry paganId ${townconf.maorId} already exist ti create a town you need a new identity, please change it`
);
process.exit();
}
*/
townconf.sudoerUser = process.env.USER; townconf.sudoerUser = process.env.USER;
townconf.dirname = path.resolve(`${__dirname}/../../`); townconf.dirname = path.resolve(`${__dirname}/../../`);
// nginx allow to set a new website space // nginx allow to set a new website space
townconf.nginx.include.push(`${townconf.dirname}/nationchains/**/nginx_*.conf`); townconf.nginx.include.push(
`${townconf.dirname}/nationchains/**/nginx_*.conf`
);
townconf.nginx.logs = `${townconf.dirname}/nationchains/logs/nginx`; townconf.nginx.logs = `${townconf.dirname}/nationchains/logs/nginx`;
townconf.nginx.website = "setup"; townconf.nginx.website = "adminapx";
townconf.nginx.fswww = "nationchains/"; //for a local tribe nationchains/tribes/tribeid townconf.nginx.fswww = "nationchains/"; //for a local tribe nationchains/tribes/tribeid
townconf.nginx.tribeid = "town"; townconf.nginx.tribeid = "town";
townconf.nginx.pageindex = "index_en.html";
console.log(townconf); console.log(townconf);
if ( if (
!readlineSync.keyInYN( !readlineSync.keyInYN(
`\x1b[42mThis is the first install from ./nationchains/www/adminapx/townconf.json (check it if you want) \nthis will change your nginx config in /etc/nginx and run nginx from sudoer user ${townconf.sudoerUser} (Yes/no)?\nno if you want to change parameter and run yarn setup again\x1b[0m` `\x1b[42mThis is the first install from ./nationchains/www/adminapx/townconf.json (check it if you want) \nthis will change your nginx config in /etc/nginx and run nginx from sudoer user ${townconf.sudoerUser} (Yes/no)? \nno if you want to change parameter and run yarn setup again \x1b[0m`
) )
) )
process.exit(); process.exit();
// saved and change nginx conf // saved and change nginx conf
if (!fs.existsSync("/etc/nginx/nginxconf.saved")) { if (!fs.existsSync("/etc/nginx/nginxconf.saved")) {
fs.moveSync("/etc/nginx/nginx.conf", "/etc/nginx/nginxconf.saved"); fs.moveSync("/etc/nginx/nginx.conf", "/etc/nginx/nginxconf.saved");
console.log("your previous /etc/nginx/nginx.conf was backup in /etc/nginx/nginxconf.saved"); console.log(
"your previous /etc/nginx/nginx.conf was backup in /etc/nginx/nginxconf.saved"
);
} }
const tplnginxconf = fs.readFileSync( const tplnginxconf = fs.readFileSync(
"./nationchains/www/adminapx/nginx/nginx.conf.mustache", "./nationchains/www/adminapx/nginx/nginx.conf.mustache",
@ -78,17 +116,58 @@ Setup.init = () => {
mustache.render(tplnginxwww, townconf), mustache.render(tplnginxwww, townconf),
"utf8" "utf8"
); );
fs.outputJsonSync("./nationchains/tribes/index/conf.json", townconf, { fs.outputJsonSync("./nationchains/tribes/conf.json", townconf, {
spaces: 2, spaces: 2,
}); });
//restart nginx //CREATE A TOWN setup local voir utiliser towns.create
townconf.town = {
townId: townconf.townId,
nationId: townconf.nationId,
url: `http://${townconf.dns[0]}`,
IP: townconf.IP,
mayorid: townconf.mayorId,
status: "unchain",
};
apxtowns[townconf.townId]=townconf.town;
fs.outputJsonSync(`./nationchains/towns/idx/townId_all.json`,apxtowns);
fs.outputJsonSync(`./nationchains/towns/itm/${townconf.townId}.json`,townconf.town,{spaces:2});
// Create tribe id voir a utiliser tribes.create()
townconf.tribe = {
tribeId: townconf.tribeId,
dns: [],
status: "unchain",
nationId: townconf.nationId,
townId: townconf.townId,
};
//tribe does not exist in a new town
apxtribes={}
apxtribes[townconf.tribeId]=townconf.tribe;
fs.outputJsonSync(`./nationchains/tribes/idx/tribeId_all.json`,apxtribes);
fs.outputJsonSync(`./nationchains/tribes/itm/${townconf.tribeId}.json`,townconf.tribe,{spaces:2});
fs.ensureDirSync(`./nationchains/tribes/${townconf.tribeId}/logs`);
//CREATE a mayorId pagans if it does not exist
if (!apxpagans[townconf.mayorId]){
const Pagans=require('./Pagans');
const createPagans=await Pagans.createId(townconf.mayorId,townconf.passphrase);
if (createPagans.status==200){
fs.outputFileSync(`./${townconf.mayorId}_PrivateKey.txt`,createPagans.data.privateKey,"utf8");
fs.outputFileSync(`./${townconf.mayorId}_PublicKey.txt`,createPagans.data.publicKey,"utf8");
console.log(`\x1b[43mCut paste your keys /${townconf.mayorId}_PrivateKey.txt /${townconf.mayorId}_PublicKey.txt \x1b[0m`)
}else{
console.log('Error at Pagan creation ');
console.log(createPagans);
process.exit();
}
}
//restart nginx
const { exec } = require("child_process"); const { exec } = require("child_process");
exec(townconf.nginx.restart, (error, stdout, stderr) => { exec(townconf.nginx.restart, (error, stdout, stderr) => {
if (error) { if (error) {
console.log("\x1b[42m", error, stdout, stderr, "x1b[0m"); console.log("\x1b[42m", error, stdout, stderr, "x1b[0m");
} else { } else {
console.log( console.log(
`\x1b[42m#########################################################################\x1b[0m\n\x1b[42mWellcome into apxtrib, you can now 'yarn dev' for dev or 'yarn startpm2' for prod or 'yarn unittest' for testing purpose.\x1b[0m \n\x1b[42m Access to your town here http://${townconf.dns} to finist your town set up.\nCheck README's project to learn more.\x1b[0m\n\x1b[42m#########################################################################\x1b[0m` `\x1b[42m###########################################################################################\x1b[0m\n\x1b[42mWellcome into apxtrib, you can now 'yarn dev' for dev or 'yarn startpm2' for prod or \n'yarn unittest' for testing purpose. Access to your town here \x1b[0m\x1b[32mhttp://${townconf.dns}\x1b[0m \x1b[42m \nto finish your town set up. Check README's project to learn more. \x1b[0m\n\x1b[42m###########################################################################################\x1b[0m`
); );
} }
}); });
@ -99,16 +178,16 @@ Setup.Checkjson = (conf) => {
const nation_town = fs.readJsonSync( const nation_town = fs.readJsonSync(
"./nationchains/socialworld/objects/towns/searchindex/towns_nation_uuid.json" "./nationchains/socialworld/objects/towns/searchindex/towns_nation_uuid.json"
); );
if (!ObjectKeys(nation_town).includes(conf.nationName)) { if (!ObjectKeys(nation_town).includes(conf.nationId)) {
rep += `your nationName ${conf.nationName} does not exist you have to choose an existing one`; rep += `your nationId ${conf.nationId} does not exist you have to choose an existing one`;
} }
if (nation_town[conf.nationName].includes(conf.townName)) { if (nation_town[conf.nationId].includes(conf.townId)) {
rep += `This conf.townName already exist you have to find a unique town name per nation`; rep += `This conf.townId already exist you have to find a unique town name per nation`;
} }
const getnation = Odmdb.get( const getnation = Odmdb.get(
"./nationchains/socialworld/objects", "./nationchains/socialworld/objects",
"towns", "towns",
[conf.NationName], [conf.NationId],
[nationId] [nationId]
); );
//if getnation.data.notfound //if getnation.data.notfound
@ -140,9 +219,9 @@ Setup.Checkjson = (conf) => {
} }
if ( if (
conf.dns != "unchain" && conf.dns != "unchain" &&
!dnsSync.resolve(`${conf.townName}.${conf.nationName}.${conf.dns}`) !dnsSync.resolve(`${conf.townId}.${conf.nationId}.${conf.dns}`)
) { ) {
rep += `\nresolving $${conf.townName}.${conf.nationName}.${conf.dns} will not responding valid IP, please setup domain redirection IP before runing this script`; rep += `\nresolving $${conf.townId}.${conf.nationId}.${conf.dns} will not responding valid IP, please setup domain redirection IP before runing this script`;
} }
return rep; return rep;
}; };

View File

@ -4,7 +4,7 @@ const glob = require( 'glob' );
const moment = require( 'moment' ); const moment = require( 'moment' );
const jwt = require( 'jwt-simple' ); const jwt = require( 'jwt-simple' );
const UUID = require( 'uuid' ); const UUID = require( 'uuid' );
const config = require( '../tribes/townconf.js' ); const conf=require('../../nationchains/tribes/conf.json')
const Checkjson = require( `./Checkjson.js`); const Checkjson = require( `./Checkjson.js`);
const Towns = {}; const Towns = {};

View File

@ -10,8 +10,7 @@ const jwt = require( 'jwt-simple' );
const moment = require( 'moment' ); const moment = require( 'moment' );
const UUID = require( 'uuid' ); const UUID = require( 'uuid' );
const Pagans = require( './Pagans.js' ); const Pagans = require( './Pagans.js' );
const config = require( '../tribes/townconf' ); const config = require( '../../nationchains/tribes/conf.json' );
const Checkjson = require( `./Checkjson.js`); const Checkjson = require( `./Checkjson.js`);
/* /*
tribeid manager tribeid manager

View File

@ -0,0 +1,5 @@
{
"schemanotfound":"Schema not found in {{{fullpath}}}",
"pathnamedoesnotexist":"ObjectPath or objectName does not exist {{{indexpath}}}",
"objectfiledoesnotexist":"Requested index does not exist here: {{{objectpath}}}"
}

View File

@ -0,0 +1,3 @@
{
}

View File

@ -1,8 +1,8 @@
const express = require( 'express' ); const express = require( 'express' );
const config = require( '../tribes/townconf.js' ); const config = require( '../../nationchains/tribes/conf.json' );
// Classes // Classes
const Nationchains = require( '../models/Nationchains.js' ); const Nations = require( '../models/Nations.js' );
// Middlewares // Middlewares
const checkHeaders = require( '../middlewares/checkHeaders' ); const checkHeaders = require( '../middlewares/checkHeaders' );
const isAuthenticated = require( '../middlewares/isAuthenticated' ); const isAuthenticated = require( '../middlewares/isAuthenticated' );

201
api/routes/odmdb.js Normal file
View File

@ -0,0 +1,201 @@
const express = require("express");
const glob = require("glob");
const fs = require("fs-extra");
const path = require("path");
const conf = require("../../nationchains/tribes/conf.json");
const Odmdb = require("../models/Odmdb.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const hasAccessrighton = require("../middlewares/hasAccessrighton");
const router = express.Router();
router.get(
"/:objectname/idx/:indexname",
checkHeaders,
isAuthenticated,
(req, res) => {
/**
* @api {get} /odmdb/idx/:indexname
* @apiName Get index file for an object
* @apiGroup Odmdb
*
* @apiUse apxHeader
* @objectname {string} Mandatory
* @apiParam {String} indexname Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname/idx/indexname indexname contains the ObjectName .*_ (before the first _)
*
* @apiError (404) {string} status the file does not exist
* @apiError (404) {string} ref objectmodel to get in the right language
* @apiError (404) {string} msg key to get template from objectmodel
* @apiError (404) {object} data use to render lg/objectmodel_lg.json
*
* @apiSuccess (200) {object} data contains indexfile requested
*
*/
// indexname = objectname_key_value.json
let objectLocation = "../../nationchains/";
if (!conf.api.nationObjects.includes(req.params.objectname)) {
objectLocation += `tribes/${req.session.headers.xtribe}/`;
// check if accessright
}
const indexpath = `${objectLocation}/${req.params.objectname}/idx/${req.params.indexname}`;
if (fs.existsSync(indexpath)) {
res.status(200).json({ data: fs.readJsonSync(indexpath) });
} else {
res
.status(404)
.json({
ref: "Odmdb",
msg: "objectfiledoesnotexist",
data: { indexpath },
});
}
}
);
router.get(
"/:objectname/itm/:primaryindex",
checkHeaders,
isAuthenticated,
(req, res) => {
/**
* @api {get} /odmdb/item/:objectname/:primaryindex
* @apiName Get index file for an object
* @apiGroup Odmdb
*
* @apiUse apxHeader
*
* @apiParam {String} objectname name Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname
* @apiParam {String} primaryindex the unique id where item is store
* @apiError (404) {string} status the file does not exist
* @apiError (404) {string} ref objectmodel to get in the right language
* @apiError (404) {string} msg key to get template from objectmodel
* @apiError (404) {object} data use to render lg/objectmodel_lg.json
*
* @apiSuccess (200) {object} data contains indexfile requested
*
*/
// indexname = objectname_key_value.json
const objectName = req.params.objectname;
const objectId = req.params.primaryindex;
let objectLocation = "../../nationchains/";
if (!conf.api.nationObjects.includes(objectName)) {
objectLocation += `tribes/${req.session.headers.xtribe}/${objectName}`;
// check if accessright on object on item
// in case not res.status(403)
}
const objectpath = `${objectLocation}/${objectName}/itm/${objectId}`;
if (fs.existsSync(objectpath)) {
res.status(200).json({ data: fs.readJsonSync(objectpath) });
} else {
res
.status(404)
.json({
ref: "Odmdb",
msg: "objectfiledoesnotexist",
data: { objectpath },
});
}
}
);
router.post(":objectname/itm", checkHeaders, isAuthenticated, (req, res) => {
// Create an item of an object
});
router.get(
"/searchitems/:objectname/:question",
checkHeaders,
isAuthenticated,
(req, res) => {
/**
*
*
*/
console.log(
"route referentials get all language" +
req.params.objectname +
"-" +
req.params.question
);
const getref = Referentials.getref(
true,
req.params.source,
req.params.idref,
req.session.header.xworkon,
req.session.header.xlang
);
// Return any status the data if any erreur return empty object
res.jsonp(getref.payload.data);
}
);
router.get("schema/:objectname", checkHeaders, isAuthenticated, (req, res) => {
/**
* @api {get} /odmdb/schema/:objectname
* @apiName GetSchema
* @apiGroup Odmdb
*
* @apiUse apxHeader
*
* @apiParam {String} objectname Mandatory if headers.xworkon == nationchains then into ./nationchains/ else into ./tribes/xworkon/
*
* @apiError (404) {string} status a key word to understand not found schema
* @apiError (404) {string} ref objectmodel to get in the right language
* @apiError (404) {string} msg key to get template from objectmodel
* @apiError (404) {object} data use to render lg/objectmodel_lg.json
*
* @apiSuccess (200) {object} data contains schema requested
*
*/
const fullpath = path.resolve(
`${__dirname}/tribes/${req.session.header.xworkon}/schema/${req.params.pathobjectname}.json`
);
if (fs.existsSync(fullpath)) {
res.status(200).json({ data: fs.readJsonSync(fullpath) });
} else {
res
.status(404)
.json({ msg: "schemanotfound", ref: "odmdb", data: { fullpath } });
}
});
router.put("schema/:objectname", checkHeaders, isAuthenticated, (req, res) => {
/**
* @api {put} /odmdb/schema/:objectname
* @apiName putSchema
* @apiGroup Odmdb
*
* @apiUse apxHeader
*
* @apiParam {String} objectname Mandatory if headers.xworkon == nationchains then into ./nationchains/ else into ./tribes/xworkon/
* @apiBody {string} schemapath where to store schema .../schema
* @apiBody {string} objectpath where to store object ...objectname/idx/config.json
* @apiBody {json} schema content
* @apiBody {json} schemalang content in lg
* @apiBody {string} lang define which schemalg is (2 letters)
*
* @apiError (404) {string} status a key word to understand not found schema
* @apiError (404) {string} ref objectmodel to get in the right language
* @apiError (404) {string} msg key to get template from objectmodel
* @apiError (404) {object} data use to render lg/objectmodel_lg.json
*
*
* @apiSuccess (200) {object} data contains schema requested
*
*/
const fullpath = path.resolve(
`${__dirname}/tribes/${req.session.header.xworkon}/schema/${req.params.pathobjectname}.json`
);
const set = Odmdb.setObject(
path.resolve(`${__dirname}/tribes/${req.session.header.xworkon}`)
);
if (fs.existsSync(fullpath)) {
res.status(200).json({ data: fs.readJsonSync(fullpath) });
} else {
res
.status(404)
.json({ msg: "schemanotfound", ref: "odmdb", data: { fullpath } });
}
});
module.exports = router;

View File

@ -46,8 +46,46 @@ Delete idem
Owner means it can be Write/Delete if field OWNER contain the UUID that try to act on this object. Usefull to allow someone to fully manage its objects. Owner means it can be Write/Delete if field OWNER contain the UUID that try to act on this object. Usefull to allow someone to fully manage its objects.
*/ */
router.get('/isregister', checkHeaders, isAuthenticated,(req,res)=>{
/**
* @api {get} /pagans/isregister
* @apiName Is register check xalias and xhash
* @apiGroup Odmdb
*
* @apiUse apxHeader
*
* @apiParam {String} indexname Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname/idx/indexname indexname contains the ObjectName .*_ (before the first _)
*
* @apiError (404) {string} status the file does not exist
* @apiError (404) {string} ref objectmodel to get in the right language
* @apiError (404) {string} msg key to get template from objectmodel
* @apiError (404) {object} data use to pagansmodel: 'Pagans' } );render lg/objectmodel_lg.json
*
* @apiSuccess (200) {object} data contains indexfile requested
*
*/
res.send(Pagans.checkdetachedSignature(req.session.header.xalias,req.session.header.xhash));
res.send({status:200,ref:"headers",msg:"authenticated",data:{xalias:req.session.header.xalias,xtribe:req.session.header.xtribe}})
})
router.post('/', checkHeaders, (req,res)=>{
// create a pagan account from alias, publickey, if trusted recovery={email,privatekey}
console.log(req.body)
} )
router.delete( '/:alias', checkHeaders, isAuthenticated, ( req, res ) => {
console.log( `DELETE pagans nationchains/pagans/${req.params.alias}.json` );
const result = Pagans.delete( req.params.id, req.session.header );
res.status( result.status )
.send( result.data );
} );
router.get( '/isauth', checkHeaders, isAuthenticated, ( req, res ) => { router.get( '/isauth', checkHeaders, isAuthenticated, ( req, res ) => {
if( req.session.header.xpaganid == "1" ) { if( req.session.header.xpseudo == "1" ) {
return res.status( 401 ) return res.status( 401 )
.send( { info: "not authenticate" } ); .send( { info: "not authenticate" } );
} else return res.status( 200 ) } else return res.status( 200 )
@ -114,14 +152,12 @@ router.get( '/getlinkwithoutpsw/:email', checkHeaders, async ( req, res ) => {
.send( getlink.data ); .send( getlink.data );
} catch ( err ) { } catch ( err ) {
console.log( err ) console.log( err )
return res.status( 500 )
.send( { info: [ 'errServer' ], model: 'Pagans' } );
} }
} }
} ); } );
router.post( '/register', checkHeaders, async ( req, res ) => { router.post( '/register', checkHeaders, async ( req, res ) => {
console.log( `POST /users for ${req.session.header.xtribe}` ); console.log( `POST /users for ${req.session.header.xtribe}` );
if( req.session.header.xauth == '123123' ) { if( req.session.header.xjwt == '123123' ) {
// Creation d'un utilisateur avec information de base aucun droit // Creation d'un utilisateur avec information de base aucun droit
// On modifie le contenu du form pour n egarder que login/email et psw // On modifie le contenu du form pour n egarder que login/email et psw
// pour le client_id permet de traiter un user en attente de validation // pour le client_id permet de traiter un user en attente de validation
@ -202,10 +238,5 @@ router.put( '/uuid/:id', checkHeaders, isAuthenticated, hasAccessrighton( 'users
.send( data ); .send( data );
} }
} ); } );
router.delete( '/uuid/:id', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'D' ), ( req, res ) => {
console.log( `DELETE /users/uuid/${req.params.id}` );
const result = Pagans.deleteUser( req.params.id, req.session.header );
res.status( result.status )
.send( result.data );
} );
module.exports = router; module.exports = router;

View File

@ -1,7 +1,7 @@
const express = require( 'express' ); const express = require( 'express' );
const fs = require( 'fs-extra' ); const fs = require( 'fs-extra' );
const path = require( 'path' ); const path = require( 'path' );
const config = require( '../tribes/townconf.js' ); const conf=require('../../nationchains/tribes/conf.json')
// Classes // Classes
const Tribes = require( '../models/Tribes.js' ); const Tribes = require( '../models/Tribes.js' );

View File

@ -1,115 +0,0 @@
const jwt = require( 'jwt-simple' );
const jsonfile = require( 'jsonfile' );
const fs = require( 'fs-extra' );
const moment = require( 'moment' );
const glob = require( 'glob' );
//const path = require( 'path' );
// Check if package is installed or not to pickup the right config file
//const src = '..'; // ( __dirname.indexOf( '/node_modules/' ) > -1 ) ? '../../..' : '..';
//const config = require( path.normalize( `${__dirname}/${src}/config.js` ) );
const config = require( '../tribes/townconf.js' );
const isAuthenticated = ( req, res, next ) => {
/*
check if authenticated with valid token
if not => set req.session.header.xauth=1
if yes => set for xWorkon
req.session.header.accessrights={
app:{'tribeid:website':[liste of menu]},
data:{ "sitewebsrc": "RWCDO",
"contacts": "RWCDO"}}
Liste of menu is linked with the app tht h
ave to be consistent with accessrights.data
data, list of object accessright Read Write Create Delete Owner
a xuuid can read any objet if R
if O wner means that it can only read write its object create by himself
*/
console.log( 'isAuthenticated()?' );
//console.log( 'req.app.locals.tokens', req.app.locals.tokens )
//console.log( 'req.session.header', req.session.header );
// Check if token exist or not
req.session.header.accessrights = { app: "", data: {} }
if( req.session.header.xpaganid == config.devnoauthxuuid && req.session.header.xauth == config.devnoauthxauth ) {
console.log( 'isAuthenticated yes: carrefull using a bypass password give you accessrights={}' );
} else if( req.session.header.xpaganid == "1" || !req.app.locals.tokens[ req.session.header.xpaganid ] ) {
console.log( `isAuthenticated no : uuid=1 (value=${req.session.header.xpaganid}) or locals.tokens[uuid] empty ` );
console.log( 'req.app.locals.tokens de xpaganid', req.app.locals.tokens[ req.session.header.xpaganid ] );
console.log( 'list key uuid de req.app.locals.tokens', Object.keys( req.app.locals.tokens ) )
req.session.header.xauth = "1"
} else if( req.app.locals.tokens[ req.session.header.xpaganid ].TOKEN !== req.session.header.xauth ) {
// console.log(req.session.header.xuuid);
// console.log(req.session.header.xauth);
// update tokens from file in case recently logged
try {
console.log( 'token not in list of token (req.app.locals.tokens) try to refresh from file' );
req.app.locals.tokens = fs.readJsonSync( `${config.tmp}/tokens.json` );
} catch ( err ) {
console.log( `check isAuthenticated issue in reading ${config.tmp}/tokens.json` );
}
if( req.app.locals.tokens[ req.session.header.xpaganid ].TOKEN !== req.session.header.xauth ) {
// if still does not exist then out
console.log( 'isAuthenticated no, token outdated' );
req.session.header.xauth = "1"
req.session.header.xpaganid = "1"
}
}
if( req.session.header.xauth == "1" ) {
//return res.status( 403 )
return res.status( 403 )
.json( {
info: [ 'forbiddenAccess' ],
model: 'Pagans',
moreinfo: 'isAuthenticated faill'
} )
} else {
console.log( 'isAuthenticated yes' );
if( req.app.locals.tokens[ req.session.header.xpaganid ] ) {
//console.log( `accessright pour ${req.session.header.xpaganid}`, req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS );
//set header.accessrights from tokens.json
req.session.header.accessrights = req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS
} else {
// case of bypass no accessright available
req.session.header.accessrights = {}
}
// Once per day, clean old token
const currentday = moment()
.date();
console.log( 'test si menagedone' + currentday, !fs.existsSync( `${config.tmp}/menagedone${currentday}` ) )
if( !fs.existsSync( `${config.tmp}/menagedone${currentday}` ) ) {
glob.sync( `${config.tmp}/menagedone*` )
.forEach( f => {
fs.remove( f, ( err ) => {
if( err ) {
console.log( 'err remove menagedone', err )
}
} )
} );
glob.sync( `${config.tmp}/mdcreator*.log` )
.forEach( f => {
fs.remove( f, ( err ) => {
if( err ) {
console.log( 'err remove mdcreator log', err )
}
} )
} );
const newtokens = {};
for( const k of Object.keys( req.app.locals.tokens ) ) {
try {
const decodedToken = jwt.decode( req.app.locals.tokens[ k ].TOKEN, config.jwtSecret );
//console.log( moment( decodedToken.expiration ), moment() )
//console.log( moment( decodedToken.expiration ) >= moment() )
if( moment( decodedToken.expiration ) >= moment() ) {
newtokens[ k ] = req.app.locals.tokens[ k ];
}
} catch ( err ) {
console.log( "Check isAuthenticated cleaning token ", err );
}
};
req.app.locals.tokens = newtokens;
fs.outputJsonSync( `${config.tmp}/tokens.json`, newtokens );
fs.writeFileSync( `${config.tmp}/menagedone${currentday}`, 'fichier semaphore to clean data each day can be deleted with no consequence', 'utf-8' );
}
next();
}
};
module.exports = isAuthenticated;

View File

@ -1,6 +0,0 @@
{
"missingheader":"This header miss to have a valid request: {{#moreinfo}} {{.}} {{/moreinfo}}",
"tribeiddoesnotexist":"Header xtribe: {{moreinfo}} does not exist",
"workondoesnotexist":"Header xworkon: {{moreinfo}} does not exist",
"forbiddenAccessright":"Pagan {{moreinfo.xpaganid}} has not access right to act {{moreinfo.action}} onto object {{moreinfo.object}} for tribe {{moreinfo.xworkon}}"
}

View File

@ -1,400 +0,0 @@
const bcrypt = require( 'bcrypt' );
const fs = require( 'fs-extra' );
const path = require( 'path' );
const jsonfile = require( 'jsonfile' );
const glob = require( 'glob' );
const Mustache = require( 'mustache' );
const jwt = require( 'jwt-simple' );
const { DateTime } = require( 'luxon' );
const UUID = require( 'uuid' );
const Outputs = require( '../models/Outputs.js' );
const config = require( '../tribes/townconf.js' );
const Checkjson = require( `./Checkjson.js`);
/*
Message manager
* Manage apxtrib message at different level
* this means that an object (most often a user or a contact) want to send a question to an other user.
To know more http://gitlab.ndda.fr/philc/apxtrib/-/wikis/HOWTONotification
*/
const Messages = {};
Messages.init = () => {
console.group( 'init Message' );
Messages.aggregate();
}
Messages.byEmailwithmailjet = ( tribeid, msg ) => {
/* @tribeid requester
@msg =[{
To:[{Email,Name}],
Cc:[{Email,Name}],
Bcc:[{Email,Name}]}],
Subject:"Subject",
TextPart:"texte content",
HTMLPart:"html content"
}]
If tribeid has a mailjet account it use it if not then it use the apxtrib @mailjetconf = {apikeypub:, apikeypriv:, From:{Email:,Name:}}
This send a bunch of messages check the mailjet account used
FYI: Basic account is 200 email /days 6000 /month
Log is stored into
tribeidsender/messages/logs/sent/timestamp.json
@todo GUI to manage statistics and notification alert limit sender email
*/
console.log( 'Envoie mailjet' )
const confclient = fs.readJsonSync( `${config.tribes}/${tribeid}/clientconf.json` );
let tribeidsender = tribeid;
if( confclient.smtp && confclient.smtp.mailjet ) {
mailjetconf = confclient.smtp.mailjet;
} else {
const confapxtrib = fs.readJsonSync( `${config.tribes}/${config.mayorId}/clientconf.json` );
if( !( confapxtrib.smtp && confapxtrib.smtp.mailjet ) ) {
return { status: 403, data: { models: "Messages", info: [ "nosmtpmailjet" ], moreinfo: "missing smtpmailjet parameter in apxtrib contact your admin to activate an mailjet account on this server." } }
}
tribeidsender = "apxtrib";
mailjetconf = confapxtrib.smtp.mailjet;
}
//add from from setings account
const MSG = msg.map( m => { m.From = mailjetconf.From; return m; } );
const mailjet = require( 'node-mailjet' )
.connect( mailjetconf.apikeypub, mailjetconf.apikeypriv );
const request = mailjet.post( 'send', { version: 'v3.1' } )
.request( { "Messages": MSG } );
request
.then( result => {
//store into tribeidsender/messages/logs/sent/timestamp.json
const t = Date.now();
MSG.result = result.body;
fs.outputJson( `${config.tribes}/${tribeidsender}/messages/logs/sent/${t}.json`, MSG )
console.log( result.body )
} )
.catch( err => {
const t = Date.now();
MSG.result = err;
fs.outputJson( `${config.tribes}/${tribeidsender}/messages/logs/error/${t}.json`, MSG )
console.log( err.statusCode, err )
} )
};
Messages.buildemail = ( tribeid, tplmessage, data ) => {
/* @tribeid => client concerned by sending email get info from clientconf.json (customization, useradmin:{ EMAIL,LOGIN} , ...)
@tplmessage => folder where template is available (ex: apxtrib/referentials/dataManagement/template/order)
@data { destemail = email to
if destuuid => then it get user EMAIL if exiat
subject = mail subject
// any relevant information for template message
msgcontenthtml = html msg content
msgcontenttxt = text msg content
....}
@return msg
mail part ready to send by mailjet or other smtp
*/
if( !fs.existsSync( `${config.tribes}/${tribeid}/clientconf.json` ) ) {
return { status: 404, data: { model: "Messages", info: [ "tribeiddoesnotexist" ], moreinfo: `${tribeid} does not exist` } }
}
if( !fs.existsSync( `${config.tribes}/${tplmessage}` ) ) {
return { status: 404, data: { model: "Messages", info: [ "tplmessagedoesnotexist" ], moreinfo: `tpl does not exist ${tplmessage}` } }
}
const clientconf = fs.readJsonSync( `${config.tribes}/${tribeid}/clientconf.json` )
//add clientconf.customization into data for template
data.customization = clientconf.customization;
//manage receiver
const msg = { To: [ { Email: clientconf.useradmin.EMAIL, Name: clientconf.useradmin.LOGIN } ] };
if( data.destemail ) {
msg.To.push( { Email: data.destemail } )
}
if( data.destuuid && fs.exist( `${config.tribes}/${tribeid}/users/${data.destuuid}.json` ) ) {
const uuidconf = fs.readJsonSync( `${config.tribes}/${tribeid}/users/${data.destuuid}.json` );
if( uuidconf.EMAIL && uuidconf.EMAIL.length > 4 ) {
msg.To.push( { Email: uuidconf.EMAIL, Name: uuidconf.LOGIN } )
}
}
//console.log( data )
// email content
msg.Subject = `Message from ${tribeid}`;
if( data.subject ) msg.Subject = data.subject;
msg.TextPart = Mustache.render( fs.readFileSync( `${config.tribes}/${data.tplmessage}/contenttxt.mustache`, 'utf-8' ), data );
msg.HTMLPart = Mustache.render( fs.readFileSync( `${config.tribes}/${data.tplmessage}/contenthtml.mustache`, 'utf-8' ), data );
return {
status: 200,
data: { model: "Messages", info: [ "msgcustomsuccessfull" ], msg: msg }
}
};
Messages.postinfo = ( data ) => {
/*
Data must have:
at least one of desttribeid:,destuuid:,destemail:
if an email have to be sent tplmessage:"tribeid/referentials/dataManagement/template/tplname",
at least one of contactemail:,contactphone,contactlogin,contactuuid
any other usefull keys
Data is stored into contacts object .json
*/
let contact = "";
[ 'contactemail', 'contactphone', 'contactuuid', 'contactlogin' ].forEach( c => {
if( data[ c ] ) contact += c + "##" + data[ c ] + "###";
} )
console.log( contact )
if( contact == "" ) {
return { status: 404, data: { model: "Messages", info: [ "contactundefine" ], moreinfo: "no contact field found in this form" } }
}
if( !data.desttribeid ) {
return { status: 404, data: { model: "Messages", info: [ "tribeidundefine" ], moreinfo: "no desttribeid field found in this form" } }
}
// save new message in contacts
let messages = {};
if( fs.existsSync( `${config.tribes}/${data.desttribeid}/contacts/${contact}.json` ) ) {
messages = fs.readJsonSync( `${config.tribes}/${data.desttribeid}/contacts/${contact}.json`, 'utf-8' );
}
messages[ Date.now() ] = data;
fs.outputJsonSync( `${config.tribes}/${data.desttribeid}/contacts/${contact}.json`, messages );
// if templatemessage exist then we send alert email
// data content have to be consistent with tplmessage to generate a clean email
if( data.tplmessage && data.tplmessage != "" &&
fs.existsSync( `${config.tribes}/${data.tplmessage}` ) ) {
if( !( data.msgtplhtml && data.msgtpltxt ) ) {
data.msgcontenthtml = `<p>${data.contactname} - ${contact.replace(/###/g,' ').replace(/##/g,":")}</p><p>Message: ${data.contactmessage}</p>`
data.msgcontenttxt = `${data.contactname} - ${contact}/nMessage:${data.contactmessage}\n`;
} else {
data.msgcontenthtml = Mustache.render( data.msgtplhtml, data )
data.msgcontenttxt = Mustache.render( data.msgtpltxt, data )
}
const msg = Messages.buildemail( data.desttribeid, data.tplmessage, data )
if( msg.status == 200 ) {
Messages.byEmailwithmailjet( data.desttribeid, [ msg.data.msg ] );
}
// we get error message eventualy but email feedback sent is not in real time
return msg;
} else {
return { status: 404, data: { info: "missingtpl", model: "Messages", moreinfo: `missing template ${data.tplmessage}` } }
}
}
Messages.aggregate = () => {
// collect each json file and add them to a global.json notifat require level
const dest = {};
try {
glob.sync( `${ config.tribes }/**/notif_*.json` )
.forEach( f => {
//console.log( 'find ', f )
const repglob = `${path.dirname(f)}/global.json`;
if( !dest[ repglob ] ) { dest[ repglob ] = [] }
dest[ repglob ].push( fs.readJsonSync( f, 'utf-8' ) );
fs.removeSync( f );
} )
//console.log( dest )
Object.keys( dest )
.forEach( g => {
let notif = [];
if( fs.existsSync( g ) ) { notif = fs.readJsonSync( g ) };
fs.writeJsonSync( g, notif.concat( dest[ g ] ), 'utf-8' );
} )
} catch ( err ) {
Console.log( "ATTENTION, des Messages risquent de disparaitre et ne sont pas traitées." );
}
}
Messages.object = ( data, header ) => {
/*
Create or replace an object no check at all here this is only
a way to add / replace object
if deeper thing have to be checheck or done then a callback:{tribeidplugin,pluginname,functionname}
data.descttribeid tribeid to send at least to admin
data.tplmessage = folder of emailtemplate
*/
console.log( 'data', data )
console.log( `${config.tribes}/${header.xworkon}/${data.object}` )
if( !fs.existsSync( `${config.tribes}/${header.xworkon}/${data.object}` ) ) {
return {
status: 404,
data: {
model: "Messages",
info: [ 'UnknownObjectfortribeid' ],
moreinfo: `This object ${data.object} does not exist for this tribeid ${header.xworkon}`
}
};
}
if( data.uuid == 0 ) {
data.uuid = UUID.v4();
}
if( data.callback ) {
// check from plugin data and add relevant data
const Plug = require( `${config.tribes}/${data.callback.tribeid}/plugins/${data.callback.plugins}/Model.js` );
const Checkjson = Plug[ data.callback.function ]( header.xworkon, data );
if( Checkjson.status == 200 ) {
data = Checkjson.data.data;
} else {
return check;
}
};
fs.outputJsonSync( `${config.tribes}/${header.xworkon}/${data.object}/${data.uuid}.json`, data );
// if templatemessage exist then we try to send alert email
if( data.tplmessage && data.tplmessage != "" &&
fs.existsSync( `${config.tribes}/${data.tplmessage}` ) ) {
const msg = Messages.buildemail( data.desttribeid, data.tplmessage, data )
if( msg.status == 200 ) {
console.log( 'WARN EMAIL DESACTIVATED CHANGE TO ACTIVATE in Messages.js' )
//Messages.byEmailwithmailjet( data.desttribeid, [ msg.data.msg ] );
}
// we get error message eventualy but email feedback sent is not in real time see notification alert in case of email not sent.
};
//Sendback data with new information
return {
status: 200,
data: {
model: "Messages",
info: [ 'Successregisterobject' ],
msg: data
}
};
}
Messages.notification = ( data, header ) => {
//check if valid notification
if( !req.body.elapseddays ) { req.body.elapseddays = 3 }
let missingkey = "";
[ 'uuid', 'title', 'desc', 'icon', 'elapseddays', 'classicon' ].forEach( k => {
if( !data[ k ] ) missingkey += ` ${k},`
if( k == "classicon" && !( [ 'text-danger', 'text-primary', 'text-success', 'text-warning', 'text-info' ].includes( data[ k ] ) ) ) {
missingkey += ` classicon is not well set ${data[k]}`;
}
} )
if( missingkey != '' ) {
return {
status: 422,
data: {
model: "Messages",
info: [ 'InvalidNote' ],
moreinfo: `invalid notification sent cause missing key ${missingkey}`
}
};
}
if( !fs.existsSync( `${config.tribes}/${header.xworkon}/${data.object}` ) ) {
return {
status: 404,
data: {
model: "Messages",
info: [ 'UnknownObjectfortribeid' ],
moreinfo: `This object ${data.object} does not exist for this tribeid ${data.tribeid}`
}
};
}
//by default store in tmp/notification this is only for sysadmin
// user adminapxtrib
let notdest = `${config.tmp}`;
if( data.app ) {
const destapp = `${config.tribes}/${data.app.split(':')[0]}/spacedev/${data.app.split(':')[1]}`;
if( fs.existsSync( destapp ) ) {
notdest = destapp;
}
}
if( data.plugins ) {
const destplugin = `${config.tribes}/${data.plugins.split(':')[0]}/plugins/${data.plugins.split(':')[1]}`;
if( fs.existsSync( destplugin ) ) {
notdest = destplugin;
}
}
if( data.object ) {
const destobject = `${config.tribes}/${data.tribeid}/${data.object}/`;
if( fs.existsSync( destobject ) ) {
notdest = destobject;
}
}
if( !data.time ) {
data.time = Date.now();
}
fs.outputJsonSync( `${notdest}/Messages/notif_${data.time}.json`, data );
return {
status: 200,
data: {
model: "Messages",
info: [ 'Successregisternotification' ],
notif: data
}
};
}
Messages.request = ( tribeid, uuid, ACCESSRIGHTS, apprequest ) => {
// list notif for each app
// list notif for each tribeid / objects if Owned
// list notif for
// check uuid notification
// Collect all notification and agregate them at relevant level;
Messages.aggregate();
//for test purpose
//const notif = fs.readJsonSync( `${config.tribes}/ndda/spacedev/mesa/src/static/components/notification/data_notiflist_fr.json` );
let notif;
if( !fs.existsSync( `${config.tribes}/${apprequest.tribeid}/spacedev/${apprequest.website}/src/static/components/notification/data_notiflist_${apprequest.lang}.json` ) ) {
// by default we send back this but this highlght an issue
notif = {
"iconnotif": "bell",
"number": 1,
"notifheader": "Your last Messages",
"notiffooter": "Check all Messages",
"actionnotifmanager": "",
"href": "?action=notification.view",
"notifs": [ {
"urldetail": "#",
"classicon": "text-danger",
"icon": "alert",
"title": `File does not exist`,
"desc": ` ${config.tribes}/${apprequest.tribeid}/spacedev/${apprequest.website}/src/static/components/notification/data_notiflist_${apprequest.lang}.json`,
"elapse": "il y a 13mn"
} ]
};
} else {
notif = fs.readJsonSync( `${config.tribes}/${apprequest.tribeid}/spacedev/${apprequest.website}/src/static/components/notification/data_notiflist_${apprequest.lang}.json` );
//clean up example notif
notif.notifs = [];
}
//check notification for plugins of tribeid of the login
glob.sync( `${config.tribes}/${tribeid}/plugins/*/Messages/global.json` )
Object.keys( ACCESSRIGHTS.app )
.forEach( a => {
// check for each app if notification about app
const appnot = `${config.tribes}/${a.split(':')[0]}/spacedev/${a.split(':')[1]}/Messages/global.json`;
if( fs.existsSync( appnot ) ) {
notif.notifs = notif.notifs.concat( fs.readJsonSync( appnot ) );
}
} );
Object.keys( ACCESSRIGHTS.plugin )
.forEach( p => {
// each plugin
if( ACCESSRIGHTS.plugin[ p ].profil == "owner" ) {
const pluginnot = `${config.tribes}/${p.split(':')[0]}/plugins/${p.split(':')[1]}/Messages/global.json`;
if( fs.existsSync( pluginnot ) ) {
notif.notifs = notif.notifs.concat( fs.readJsonSync( pluginnot ) );
}
}
} );
Object.keys( ACCESSRIGHTS.data )
.forEach( c => {
// each tribeid
Object.keys( ACCESSRIGHTS.data[ c ] )
.forEach( o => {
const cliobjnot = `${config.tribes}/${c}/${o}/Messages/global.json`
//check for each tribeid / Object per accessright user
if( fs.existsSync( cliobjnot ) ) {
console.log( `droit sur client ${c} objet ${o} : ${ACCESSRIGHTS.data[ c ][ o ]}` );
//check if intersection between user accessrigth for this object and the notification accessright is not empty @Todo replace true by intersec
console.log( 'WARN no actif filter all notif are shared with any authenticated user' )
const newnotif = fs.readJsonSync( cliobjnot )
.filter( n => { return true } );
notif.notifs = notif.notifs.concat( newnotif );
}
} )
} )
return {
status: 200,
data: {
model: "Messages",
info: [ 'successgetnotification' ],
notif: notif
}
};
}
module.exports = Messages;

View File

@ -1,557 +0,0 @@
const fs = require( 'fs-extra' );
const path = require( 'path' );
const formidable = require( 'formidable' );
const jsonfile = require( 'jsonfile' );
const mustache = require( 'mustache' );
const moment = require( 'moment' );
const UUID = require( 'uuid' );
const pdf = require( "pdf-creator-node" );
const nodemailer = require( 'nodemailer' );
const smtpTransport = require( 'nodemailer-smtp-transport' );
const axios = require( 'axios' );
const { GoogleSpreadsheet } = require( 'google-spreadsheet' );
const config = require( '../tribes/townconf.js' );
const Checkjson = require( `./Checkjson.js` );
const Outputs = {};
Outputs.ggsheet2json = async ( req, header ) => {
/*
req.ggsource = key name of the ggsheet into clientconf
req.sheets = [list of sheet names to import]
into /ggsheets/ ggsource.json = {resultfolder,productIdSpreadsheet,
googleDriveCredentials}
*/
if( !fs.existsSync( `${config.tribes}/${header.xworkon}/${req.ggsource}` ) ) {
// Misconfiguration
return {
status: 404,
payload: {
data: {},
info: [ 'Misconfiguration' ],
moreinfo: `${header.xworkon}/${req.ggsource} missing file check gitlabdocumentation`,
model: 'Outputs'
}
};
}
const confgg = fs.readJsonSync( `${config.tribes}/${header.xworkon}/${req.ggsource}`, 'utf-8' )
//const ggconnect = clientconf.ggsheet[ req.ggsource ]
//googleDriveCredentials;
//console.log( ggconnect )
doc = new GoogleSpreadsheet( confgg.productIdSpreadsheet );
await doc.useServiceAccountAuth( confgg.googleDriveCredentials );
await doc.loadInfo();
let result = [];
let invalidfor = "";
//console.log( "sheets", req.sheets );
for( const sheetName of req.sheets ) {
console.log( 'loading: ', sheetName );
if( !doc.sheetsByTitle[ sheetName ] ) {
invalidfor += " " + sheetName;
} else {
sheet = doc.sheetsByTitle[ sheetName ]
await sheet.loadHeaderRow();
const records = await sheet.getRows( { offset: 1 } )
records.forEach( record => {
let offer = {}
for( let index = 0; index < record._sheet.headerValues.length; index++ ) {
offer[ record._sheet.headerValues[ index ] ] = record[ record._sheet.headerValues[ index ] ];
}
result.push( offer );
} );
}
}
const idfile = UUID.v4();
fs.outputJsonSync( `${config.tribes}/${header.xworkon}/${confgg.resultfolder}/${idfile}.json`, result, 'utf8' );
if( invalidfor == "" ) {
return {
status: 200,
payload: {
data: `${confgg.resultfolder}/${idfile}.json`,
info: [ 'Successfull' ],
model: 'Outputs'
}
}
} else {
return {
status: 207,
payload: {
data: `${confgg.resultfolder}/${idfile}.json`,
info: [ 'PartialySuccessfull' ],
moreinfo: `Following sheetNames does not exist :${invalidfor}`,
model: 'Outputs'
}
}
};
};
// REVOIR TOUT CE QU'IL Y A EN DESSOUS et ré-écrire avec la logique de ggsheet2json phil 25/10/2021
///////////////////////////////////////////////////
const sleep = ( milliseconds = 500 ) => new Promise( resolve => setTimeout( resolve, milliseconds ) );
/*
Process any data to a specific output:
emailer => generate a finale text file to send
csv => export json file to csv data
pdf => generate a customized document
*/
Outputs.envoiemail = async ( msg, nowait, nbfois ) => {
// console.log('{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}');
// console.log('msg to send', msg);
console.log( 'nbfois', nbfois );
let transporter = nodemailer.createTransport( msg.smtp );
if( !nowait ) {
console.log( 'attente 1er msg avant d envoyer les autres' );
const transport = await transporter.verify();
console.log( 'transport', transport );
if( transport.error ) {
console.log( 'Probleme de smtp', error );
return {
status: 500,
payload: {
info: ''
}
};
} else {
let rep = await transporter.sendMail( msg );
console.log( 'rep sendMail', rep );
if( rep.accepted && rep.accepted.length > 0 && rep.rejected.length == 0 ) {
fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_success.txt`, moment( new Date() )
.format( 'YYYYMMDD HH:mm:ss' ) + ' - Success after waiting 1st email to send ' + msg.to + '\n', 'utf-8' );
return {
status: '200',
payload: {
info: [ 'send1stemailok' ],
model: 'Outputs'
}
};
}
// status à tester si necessaire de detecter une erreur
// if (rep.rejectedErrors) {
fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_error.txt`, moment( new Date() )
.format( 'YYYYMMDD HH:mm:ss' ) + ' - err after waiting result\n ' + msg.to, 'utf-8' );
return {
status: '500',
payload: {
info: [ 'rejectedError' ],
model: 'Outputs'
}
};
}
} else {
transporter.sendMail( msg, async ( err, info ) => {
if( err ) {
if( nbfois < 4 ) {
console.log( 'nouvelle tentative ', nbfois );
await sleep( 600000 ); // attends 60sec pour faire une niéme tentative
Outputs.envoiemail( msg, true, nbfois + 1 );
} else {
// logerror in file
console.log( 'err', err )
fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_error.txt`, moment( new Date() )
.format( 'YYYYMMDD HH:mm:ss' ) + ' - err after 4 tries to ' + info.rejected.join( ',' ) + '\n', 'utf-8' );
// console.log('msg.to not well sent', msg.to);
}
} else {
console.log( 'info', info )
// console.log('msg.to well sent', msg.to);
fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_success.txt`, moment( new Date() )
.format( 'YYYYMMDD HH:mm:ss' ) + ' - Success after ' + nbfois + ' tries to ' + info.accepted.join( ',' ) + '\n', 'utf-8' );
}
} );
}
// return something to not wait the rest of email
return {
status: '200',
payload: {
info: [ 'send1stemailok' ],
model: 'Outputs'
}
};
};
Outputs.generemsg = async ( msg, header ) => {
/*
wait msg sent and return result sent
*/
// Recupere les parametre smtp du domainName à utiliser
console.log( 'pass Outputs.generemsg' )
try {
const confclientexpediteur = fs.readJsonSync( `${config.tribes}/${msg.tribeidperso.tribeidexpediteur}/clientconf.json` );
//console.log('expediteur', confclientexpediteur);
msg.smtp = confclientexpediteur.smtp;
/* const confclient = fs.readJsonSync(
`${config.tribes}/${msg.tribeidperso.tribeid}/clientconf.json`
);*/
} catch ( err ) {
console.log( 'la conf smtp du client n\'est pas definie' );
return {
status: 404,
payload: {
info: [ 'smtpnotdefined' ],
model: 'Outputs'
}
};
}
console.log( msg );
if( !msg.template.sendascontent && msg.template.htmlfile ) {
try {
msg.template.html = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache', 'utf-8' );
msg.template.text = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contenttxt.mustache', 'utf-8' );
} catch ( err ) {
console.log( 'WARNING, html file template missing ' + config.sharedData + '/' + msg.template.htmlfile );
console.log( err );
return {
status: 404,
payload: {
info: [ 'fileUnknown' ],
model: 'UploadFiles',
moreinfo: 'Template unavailable, check ' + config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache and contenttxt.mustache'
}
};
}
}
if( msg.template.html.length == 0 ) {
console.log( 'template.html est vide' )
return {
status: 404,
payload: {
info: [ 'ERRnotemplate' ],
model: 'Outputs',
moreinfo: 'No template email check '
}
};
}
// mustache any data into
// console.log(msg);
const msg2send = {};
msg2send.smtp = msg.smtp;
msg2send.from = msg.tribeidperso.from;
if( msg.tribeidperso.cc ) msg2send.cc = msg.tribeidperso.cc;
if( msg.tribeidperso.bcc ) msg2send.bcc = msg.tribeidperso.bcc;
if( msg.tribeidperso.replyTo ) msg2send.replyTo = msg.tribeidperso.replyTo;
msg2send.headers = {
'x-campaign-id': msg.tribeidperso.messageId,
'x-client-nd-id': msg.tribeidperso.tribeid,
'x-template-nd-id': msg.tribeidperso.templateId
};
// we get in datacust= {tribeidperso: with clientconf,destperso: personnalise data to send for email}
// console.log(msg);
console.log( 'nb de message to send:', msg.destperso.length );
//console.log(msg.destperso);
//msg.destperso.forEach(async (perso, pos) => {
let pos;
let pass1ermsg = false;
for( pos = 0; pos < msg.destperso.length; pos++ ) {
const datacust = {
tribeidperso: msg.tribeidperso,
destperso: msg.destperso[ pos ]
};
// Evaluation of each field if mustache exist
const datacusteval = {};
Object.keys( datacust.tribeidperso )
.forEach( k => {
if( typeof datacust.tribeidperso[ k ] === 'string' || datacust.tribeidperso[ k ] instanceof String ) {
datacusteval[ k ] = mustache.render( datacust.tribeidperso[ k ], datacust )
} else {
datacusteval[ k ] = datacust.tribeidperso[ k ];
}
} )
Object.keys( datacust.destperso )
.forEach( k => {
if( typeof datacust.destperso[ k ] === 'string' || datacust.destperso[ k ] instanceof String ) {
datacusteval[ k ] = mustache.render( datacust.destperso[ k ], datacust )
} else {
datacusteval[ k ] = datacust.destperso[ k ];
}
} )
msg2send.to = msg.destperso[ pos ].email;
console.log( 'msg2send.to ' + msg2send.to + ' pos:' + pos );
// console.log('avec datacusteval ', datacusteval)
msg2send.subject = mustache.render( msg.template.subject, datacusteval );
msg2send.text = mustache.render( msg.template.text, datacusteval );
msg2send.html = mustache.render( msg.template.html, datacusteval );
let nowait = true;
if( config.emailerurl == 'http://devapia.maildigit.fr:3015' ) {
fs.writeFileSync( 'devdata/tmp/test.html', msg2send.html, 'utf-8' );
console.log( 'lancement email sur dev, pour controler le mail générer voir ds ./config.js il faut changer config.emailerurl avec https://mail.maildigit.fr pour envoyer le mail ' )
return {
status: 200,
payload: {
info: [ 'msgsentok' ],
model: 'Outputs',
moreinfo: "parametrer sur emailer de dev et pas de production"
}
}
}
if( pos == 0 ) {
nowait = false;
/* we are waiting the first email was sent ok then we send all other
check NEEDDATA/OVH/workspace/emailerovh to send emailer with nodemailer and nodemailer-smtp-transport
*/
// console.log('envoie msg', msg);
//console.log(msg2send);
const ret = await Outputs.envoiemail( msg2send, nowait, 0 );
console.log( 'ret 1er msg', ret );
if( ret.status == 200 ) {
pass1ermsg = true;
};
} else if( pass1ermsg ) {
console.log( '###############################################' )
console.log( "envoie msg numero: " + pos + " email: " + msg2send.to )
//console.log(msg2send)
Outputs.envoiemail( msg2send, nowait, 0 );
/*Outputs.envoiemail(msg2send, nowait, 0).then(rep => {
console.log("envoie email" + pos)
}).catch(err => {
console.log(err);
});*/
};
};
if( pass1ermsg ) {
return {
status: 200,
payload: {
info: [ 'msgsentok' ],
model: 'Outputs'
}
};
} else {
return {
status: 500,
payload: {
info: [ 'msgsentko' ],
model: 'Ouputs',
moreinfo: "1er msg non envoyé car erreur"
}
}
}
};
Outputs.sendMailcampain = async ( msg, headersmsg ) => {
/*
Permet de lancer une campagne de mail personnalisé en mode web service
avec axios config.emailerurl https://mail qui peut être sur un autre serveur que celui en cours
Attention headermsg doit être retraduit avec les champs envoyé par un navigateur
Si le serveur en cours appelle cette fonction les champs du header doivent changer
voir config.js node_env .exposedHeaders
Pour un exemple de msg voir u exemple type de message envoyé dans un tribeid/domain/clientconf.json
avec l'envoi d'email
*/
//console.log(msg)
// On ajoute le contenu du template directement dans la demande
if( msg.template.sendascontent && msg.template.htmlfile ) {
try {
console.log( 'test', msg.template.sendascontent )
msg.template.html = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache', 'utf-8' );
msg.template.text = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contenttxt.mustache', 'utf-8' );
} catch ( err ) {
console.log( 'WARNING, html file template missing ' + config.sharedData + '/' + msg.template.htmlfile );
//console.log(err);
return {
status: 404,
payload: {
info: [ 'fileUnknown' ],
model: 'UploadFiles',
moreinfo: 'Template unavailable, check ' + config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache and contenttxt.mustache'
}
};
}
delete msg.template.htmlfile;
if( msg.template.html.length == 0 ) {
return {
status: 404,
payload: {
info: [ 'ERRnotemplate' ],
model: 'Outputs',
moreinfo: 'No template email check '
}
};
}
}
console.log( 'envoie sur', `${config.emailerurl}/outputs/msg` )
//console.log(msg)
// on check si les key de headermsg sont des key traduite via exposedHeaders
// (cas ou c'est l'application qui envoie un email)
if( headersmsg.xtribeid ) {
Object.keys( config.exposedHeaders )
.forEach( h => {
headersmsg[ h ] = headersmsg[ config.exposedHeaders[ h ] ];
delete headersmsg[ config.exposedHeaders[ h ] ];
} );
}
// on ajoute le code pour la signature
headersmsg.hashbody = msg.code;
console.log( 'header after traduction: ', headersmsg )
try {
const resCamp = await axios.post( `${config.emailerurl}/outputs/msg`, msg, {
headers: headersmsg
} );
//console.log('Etat:', resCamp);
console.log( 'Tried to send 1st email of the campain ' + msg.destperso[ 0 ].email );
// it just check the 1st email in destperso to return an answer if 1st is ok then all other are send in queue
if( resCamp ) {
return resCamp;
} else {
return { status: 200, payload: { info: [ 'CampainSent' ], model: 'Outputs' } };
}
} catch ( err ) {
// aios error handler
return { status: 401, payload: { info: [ 'erreuraxios' ], model: 'Outputs', moreinfo: err.message } }
}
};
Outputs.get = function ( filename, header ) {
// check file exist
const file = `${config.tribes}/${header.xworkon}/${filename}`;
// console.log('fichier demande ', file);
if( !fs.existsSync( file ) ) {
// console.log('le fichier demande n existe pas ', file);
return {
status: 404,
payload: {
info: [ 'fileUnknown' ],
model: 'UploadFiles'
}
};
} else {
console.log( 'envoie le fichier ', file );
return {
status: 200,
payload: {
info: [ 'fileknown' ],
model: 'UploadFiles',
file: file
}
};
}
};
Outputs.addjson = function ( data, header ) {
/*
Le header = {X-WorkOn:"",destinationfile:"", filename:""}
Le body = {jsonp:{},callback:function to launch after download,'code':'mot cle pour verifier que le fichier est à garder'}
*/
// console.log(req.body.jsonp);
try {
fs.outputJsonSync( header.destinationfile + '/' + header.filename, data.jsonp );
if( data.callback ) {
const execCB = require( `${__base}/models/tribeid/${header.xworkon
}` );
execCB[ data.callback ]();
}
return {
status: 200,
payload: {
info: [ 'wellUpload' ],
model: 'UploadFiles',
render: {
destination: header.destinationfile,
filename: header.filename
}
}
};
} catch ( err ) {
console.log( 'Impossible de sauvegarder le fichier, A COMPRENDRE', err );
return {
status: 503,
payload: {
info: [ 'savingError' ],
model: 'UploadFiles'
}
};
}
};
Outputs.add = function ( req, header ) {
const form = new formidable.IncomingForm();
console.log( 'req.headers', req.headers );
console.log( 'req.params', req.params );
console.log( 'req.query', req.query );
console.log( 'req.body', req.body );
let destinationfile = `${config.tribes}/${header.xworkon}/${header.destinationfile
}`;
form.parse( req, function ( err, fields, files ) {
console.log( 'files', files.file.path );
console.log( 'fields', fields );
const oldpath = files.file.path;
destinationfile += '/' + files.file.name;
console.log( 'oldpath', oldpath );
console.log( 'destinationfile', destinationfile );
fs.copyFile( oldpath, destinationfile, function ( err ) {
if( err ) {
console.log( err );
return {
status: 500,
payload: {
info: [ 'savingError' ],
model: 'UploadFiles'
}
};
} else {
console.log( 'passe' );
fs.unlink( oldpath );
return {
status: 200,
payload: {
info: [ 'wellUpload' ],
model: 'UploadFiles',
render: {
destination: destinationfile
}
}
};
}
} );
} );
};
Outputs.generepdf = ( req, header ) => {
return new Promise( ( resolve, reject ) => {
let options = {
format: "A4",
orientation: "portrait",
border: "10mm",
footer: {
height: "20mm",
contents: {
default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // html pagination if edit needed
}
}
};
let document = {
html: req.html,
data: {
data: req.data,
},
path: `${config.tribes}/${header.xtribe}/outputs/${UUID.v4()}.pdf`,
type: "",
};
pdf // generate pdf
.create( document, options )
.then( ( res ) => {
resolve( {
status: 200,
payload: {
info: [ 'wellPdfGenerated' ],
model: 'Outputs',
data: {
path: document.path,
filename: req.data.filename
},
render: {
filename: req.data.filename
}
}
} );
} )
.catch( ( err ) => {
reject( {
status: 500,
payload: {
info: [ 'pdfGenerationError' ],
model: 'Outputs',
error: err
}
} );
} );
} );
};
module.exports = Outputs;

View File

@ -1,492 +0,0 @@
const fs = require( 'fs-extra' );
const path = require( 'path' );
const formidable = require( 'formidable' );
const jsonfile = require( 'jsonfile' );
const mustache = require( 'mustache' );
const moment = require( 'moment' );
const UUID = require( 'uuid' );
const pdf = require( "pdf-creator-node" );
const nodemailer = require( 'nodemailer' );
const smtpTransport = require( 'nodemailer-smtp-transport' );
const axios = require( 'axios' );
const { GoogleSpreadsheet } = require( 'google-spreadsheet' );
const async = require( 'async' );
const config = require( '../tribes/townconf.js' );
const Checkjson = require( `${config.tribes}/${config.mayorId}/www/cdn/public/js/Checkjson` );
const Outputs = {};
const sleep = ( milliseconds = 500 ) => new Promise( resolve => setTimeout( resolve, milliseconds ) );
/*
Process any data to a specific output:
emailer => generate a finale text file to send
csv => export json file to csv data
pdf => generate a customized document
*/
Outputs.envoiemail = ( msg, next ) => {
let transporter = nodemailer.createTransport( msg.smtp );
transporter.sendMail( msg, async ( err, info ) => {
if( err ) {
next( err );
} else {
console.log( 'info', info )
fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_success.txt`, moment( new Date() )
.format( 'YYYYMMDD HH:mm:ss' ) + ' - Success after ' + '0' + ' tries to ' + info.accepted.join( ',' ) + '\n', 'utf-8' );
next( null );
}
} );
};
Outputs.setupmail = ( msg, msg2send, index ) => {
const datacust = {
tribeidperso: msg.tribeidperso,
destperso: index
};
// Evaluation of each field if mustache exist
const datacusteval = {};
Object.keys( datacust.tribeidperso )
.forEach( k => {
if( typeof datacust.tribeidperso[ k ] === 'string' || datacust.tribeidperso[ k ] instanceof String ) {
datacusteval[ k ] = mustache.render( datacust.tribeidperso[ k ], datacust )
} else {
datacusteval[ k ] = datacust.tribeidperso[ k ];
}
} )
Object.keys( datacust.destperso )
.forEach( k => {
if( typeof datacust.destperso[ k ] === 'string' || datacust.destperso[ k ] instanceof String ) {
datacusteval[ k ] = mustache.render( datacust.destperso[ k ], datacust )
} else {
datacusteval[ k ] = datacust.destperso[ k ];
}
} )
msg2send.to = index.email;
console.log( 'msg2send.to ' + msg2send.to );
msg2send.subject = mustache.render( msg.template.subject, datacusteval );
msg2send.text = mustache.render( msg.template.text, datacusteval );
msg2send.html = mustache.render( msg.template.html, datacusteval );
// TODO need to move that in generemsg
// if (config.emailerurl == 'http://devapia.maildigit.fr:3015') {
// fs.writeFileSync('devdata/tmp/test.html', msg2send.html, 'utf-8');
// console.log('lancement email sur dev, pour controler le mail générer voir ds ./config.js il faut changer config.emailerurl avec https://mail.maildigit.fr pour envoyer le mail ')
// return {
// status: 200,
// payload: {
// info: ['msgsentok'],
// model: 'Outputs',
// moreinfo: "parametrer sur emailer de dev et pas de production"
// }
// }
// }
return msg2send;
}
Outputs.envoiefirstmail = async ( msg ) => {
console.log( '###############################################' )
console.log( "envoie first msg email: " + msg.to )
let transporter = nodemailer.createTransport( msg.smtp );
console.log( 'attente 1er msg avant d envoyer les autres' );
const transport = await transporter.verify();
console.log( 'transport', transport );
if( transport.error ) {
console.log( 'Probleme de smtp', error );
return {
status: 500,
payload: {
info: ''
}
};
} else {
let rep = await transporter.sendMail( msg );
console.log( 'rep sendMail', rep );
if( rep.accepted && rep.accepted.length > 0 && rep.rejected.length == 0 ) {
fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_success.txt`, moment( new Date() )
.format( 'YYYYMMDD HH:mm:ss' ) + ' - Success after waiting 1st email to send ' + msg.to + '\n', 'utf-8' );
return {
status: '200',
payload: {
info: [ 'send1stemailok' ],
model: 'Outputs'
}
};
}
// status à tester si necessaire de detecter une erreur
// if (rep.rejectedErrors) {
fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_error.txt`, moment( new Date() )
.format( 'YYYYMMDD HH:mm:ss' ) + ' - err after waiting result\n ' + msg.to, 'utf-8' );
return {
status: '500',
payload: {
info: [ 'rejectedError' ],
model: 'Outputs'
}
};
}
}
Outputs.envoiemails = ( msg, msg2send, targets, iteration, resolve, reject ) => {
let newtargets = [];
async.each( targets, ( index, callback ) => { // iterate asynchronously in msg.destperso (targets)
let finalmsg = Outputs.setupmail( msg, msg2send, index );
console.log( '###############################################' )
console.log( "envoie msg email: " + finalmsg.to )
Outputs.envoiemail( finalmsg, ( err ) => {
if( err ) { // intentionally don't pass this error in callback, we dont want to break loop
newtargets.push( index ); // stock all errored mails for next try
}
} );
callback();
}, function ( err ) { // part executed only once all iterations are done
if( newtargets.length > 0 && iteration < 4 ) {
setTimeout( () => {
Outputs.envoiemails( msg, msg2send, newtargets, iteration + 1, resolve, reject );
}, 600000 );
} else resolve( newtargets ); // return not resolved errors after 4 trys for log
} );
}
Outputs.generemsg = async ( msg, header ) => {
/*
wait msg sent and return result sent
*/
// Recupere les parametre smtp du domainName à utiliser
console.log( 'pass Outputs.generemsg' )
try {
const confclientexpediteur = fs.readJsonSync( `${config.tribes}/${msg.tribeidperso.tribeidexpediteur}/clientconf.json` );
msg.smtp = confclientexpediteur.smtp;
} catch ( err ) {
console.log( 'la conf smtp du client n\'est pas definie' );
return {
status: 404,
payload: {
info: [ 'smtpnotdefined' ],
model: 'Outputs'
}
};
}
console.log( msg );
if( !msg.template.sendascontent && msg.template.htmlfile ) {
try {
msg.template.html = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache', 'utf-8' );
msg.template.text = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contenttxt.mustache', 'utf-8' );
} catch ( err ) {
console.log( 'WARNING, html file template missing ' + config.sharedData + '/' + msg.template.htmlfile );
console.log( err );
return {
status: 404,
payload: {
info: [ 'fileUnknown' ],
model: 'UploadFiles',
moreinfo: 'Template unavailable, check ' + config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache and contenttxt.mustache'
}
};
}
}
if( msg.template.html.length == 0 ) {
console.log( 'template.html est vide' )
return {
status: 404,
payload: {
info: [ 'ERRnotemplate' ],
model: 'Outputs',
moreinfo: 'No template email check '
}
};
}
// mustache any data into
const msg2send = {};
msg2send.smtp = msg.smtp;
msg2send.from = msg.tribeidperso.from;
if( msg.tribeidperso.cc ) msg2send.cc = msg.tribeidperso.cc;
if( msg.tribeidperso.bcc ) msg2send.bcc = msg.tribeidperso.bcc;
if( msg.tribeidperso.replyTo ) msg2send.replyTo = msg.tribeidperso.replyTo;
msg2send.headers = {
'x-campaign-id': msg.tribeidperso.messageId,
'x-client-nd-id': msg.tribeidperso.tribeid,
'x-template-nd-id': msg.tribeidperso.templateId
};
console.log( 'nb de message to send:', msg.destperso.length );
// send first mail
const ret = await Outputs.envoiefirstmail( Outputs.setupmail( msg, msg2send, msg.destperso[ 0 ] ) );
console.log( 'ret 1er msg', ret );
if( ret.status == 200 ) {
pass1ermsg = true;
msg.destperso.shift();
};
console.log( 'attente 1er msg avant d envoyer les autres' );
// send other mails
new Promise( ( resolve, reject ) => { // useless promise used for recursive calls in Outputs.envoiemails
Outputs.envoiemails( msg, msg2send, msg.destperso, 0, resolve, reject );
} )
.then( ( result ) => {
async.eachSeries( result, ( index, callback ) => { // variante of each but runs only a single operation at a time because of fs.appendFile
fs.appendFile( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_error.txt`, moment( new Date() )
.format( 'YYYYMMDD HH:mm:ss' ) + ' - err after 4 tries to ' + info.rejected.join( ',' ) + '\n', 'utf-8', ( err ) => {
callback( err );
}, ( err ) => {
if( err ) console.log( err );
} );
console.log( 'msg.to not well sent', msg.to );
} );
} )
if( pass1ermsg ) {
return {
status: 200,
payload: {
info: [ 'msgsentok' ],
model: 'Outputs'
}
};
} else {
return {
status: 500,
payload: {
info: [ 'msgsentko' ],
model: 'Ouputs',
moreinfo: "1er msg non envoyé car erreur"
}
}
}
};
Outputs.sendMailcampain = async ( msg, headersmsg ) => {
/*
Permet de lancer une campagne de mail personnalisé en mode web service
avec axios config.emailerurl https://mail qui peut être sur un autre serveur que celui en cours
Attention headermsg doit être retraduit avec les champs envoyé par un navigateur
Si le serveur en cours appelle cette fonction les champs du header doivent changer
voir config.js node_env .exposedHeaders
Pour un exemple de msg voir u exemple type de message envoyé dans un tribeid/domain/clientconf.json
avec l'envoi d'email
*/
//console.log(msg)
// On ajoute le contenu du template directement dans la demande
if( msg.template.sendascontent && msg.template.htmlfile ) {
try {
console.log( 'test', msg.template.sendascontent )
msg.template.html = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache', 'utf-8' );
msg.template.text = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contenttxt.mustache', 'utf-8' );
} catch ( err ) {
console.log( 'WARNING, html file template missing ' + config.sharedData + '/' + msg.template.htmlfile );
//console.log(err);
return {
status: 404,
payload: {
info: [ 'fileUnknown' ],
model: 'UploadFiles',
moreinfo: 'Template unavailable, check ' + config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache and contenttxt.mustache'
}
};
}
delete msg.template.htmlfile;
if( msg.template.html.length == 0 ) {
return {
status: 404,
payload: {
info: [ 'ERRnotemplate' ],
model: 'Outputs',
moreinfo: 'No template email check '
}
};
}
}
console.log( 'envoie sur', `${config.emailerurl}/outputs/msg` )
//console.log(msg)
// on check si les key de headermsg sont des key traduite via exposedHeaders
// (cas ou c'est l'application qui envoie un email)
if( headersmsg.xtribeid ) {
Object.keys( config.exposedHeaders )
.forEach( h => {
headersmsg[ h ] = headersmsg[ config.exposedHeaders[ h ] ];
delete headersmsg[ config.exposedHeaders[ h ] ];
} );
}
// on ajoute le code pour la signature
headersmsg.hashbody = msg.code;
console.log( 'header after traduction: ', headersmsg )
try {
const resCamp = await axios.post( `${config.emailerurl}/outputs/msg`, msg, {
headers: headersmsg
} );
//console.log('Etat:', resCamp);
console.log( 'Tried to send 1st email of the campain ' + msg.destperso[ 0 ].email );
// it just check the 1st email in destperso to return an answer if 1st is ok then all other are send in queue
if( resCamp ) {
return resCamp;
} else {
return { status: 200, payload: { info: [ 'CampainSent' ], model: 'Outputs' } };
}
} catch ( err ) {
// aios error handler
return { status: 401, payload: { info: [ 'erreuraxios' ], model: 'Outputs', moreinfo: err.message } }
}
};
Outputs.get = function ( filename, header ) {
// check file exist
const file = `${config.tribes}/${header.xworkon}/${filename}`;
// console.log('fichier demande ', file);
if( !fs.existsSync( file ) ) {
// console.log('le fichier demande n existe pas ', file);
return {
status: 404,
payload: {
info: [ 'fileUnknown' ],
model: 'UploadFiles'
}
};
} else {
console.log( 'envoie le fichier ', file );
return {
status: 200,
payload: {
info: [ 'fileknown' ],
model: 'UploadFiles',
file: file
}
};
}
};
Outputs.addjson = function ( data, header ) {
/*
Le header = {X-WorkOn:"",destinationfile:"", filename:""}
Le body = {jsonp:{},callback:function to launch after download,'code':'mot cle pour verifier que le fichier est à garder'}
*/
// console.log(req.body.jsonp);
try {
fs.outputJsonSync( header.destinationfile + '/' + header.filename, data.jsonp );
if( data.callback ) {
const execCB = require( `${__base}/models/tribeid/${header.xworkon
}` );
execCB[ data.callback ]();
}
return {
status: 200,
payload: {
info: [ 'wellUpload' ],
model: 'UploadFiles',
render: {
destination: header.destinationfile,
filename: header.filename
}
}
};
} catch ( err ) {
console.log( 'Impossible de sauvegarder le fichier, A COMPRENDRE', err );
return {
status: 503,
payload: {
info: [ 'savingError' ],
model: 'UploadFiles'
}
};
}
};
Outputs.add = function ( req, header ) {
const form = new formidable.IncomingForm();
console.log( 'req.headers', req.headers );
console.log( 'req.params', req.params );
console.log( 'req.query', req.query );
console.log( 'req.body', req.body );
let destinationfile = `${config.tribes}/${header.xworkon}/${header.destinationfile
}`;
form.parse( req, function ( err, fields, files ) {
console.log( 'files', files.file.path );
console.log( 'fields', fields );
const oldpath = files.file.path;
destinationfile += '/' + files.file.name;
console.log( 'oldpath', oldpath );
console.log( 'destinationfile', destinationfile );
fs.copyFile( oldpath, destinationfile, function ( err ) {
if( err ) {
console.log( err );
return {
status: 500,
payload: {
info: [ 'savingError' ],
model: 'UploadFiles'
}
};
} else {
console.log( 'passe' );
fs.unlink( oldpath );
return {
status: 200,
payload: {
info: [ 'wellUpload' ],
model: 'UploadFiles',
render: {
destination: destinationfile
}
}
};
}
} );
} );
};
Outputs.sheettojson = async ( req, header ) => {
doc = new GoogleSpreadsheet( req.productIdSpreadsheet );
await doc.useServiceAccountAuth( req.googleDriveCredentials );
await doc.loadInfo();
let result = [];
for( const sheetName of req.sheets ) {
console.log( 'loading: ', sheetName );
sheet = doc.sheetsByTitle[ sheetName ]
await sheet.loadHeaderRow();
const records = await sheet.getRows( { offset: 1 } )
records.forEach( record => {
let offer = {}
for( let index = 0; index < record._sheet.headerValues.length; index++ ) {
offer[ record._sheet.headerValues[ index ] ] = record[ record._sheet.headerValues[ index ] ];
}
result.push( offer );
} );
}
return result;
};
Outputs.generepdf = ( req, header ) => {
return new Promise( ( resolve, reject ) => {
let options = {
format: "A4",
orientation: "portrait",
border: "10mm",
footer: {
height: "20mm",
contents: {
default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // html pagination if edit needed
}
}
};
let document = {
html: req.html,
data: {
data: req.data,
},
path: `${config.tribes}/${header.xtribeid}/outputs/${UUID.v4()}.pdf`,
type: "",
};
pdf // generate pdf
.create( document, options )
.then( ( res ) => {
resolve( {
status: 200,
payload: {
info: [ 'wellPdfGenerated' ],
model: 'Outputs',
data: {
path: document.path,
filename: req.data.filename
},
render: {
filename: req.data.filename
}
}
} );
} )
.catch( ( err ) => {
reject( {
status: 500,
payload: {
info: [ 'pdfGenerationError' ],
model: 'Outputs',
error: err
}
} );
} );
} );
};
module.exports = Outputs;

View File

@ -1,773 +0,0 @@
const bcrypt = require( 'bcrypt' );
const fs = require( 'fs-extra' );
const glob = require( 'glob' );
const moment = require( 'moment' );
const jwt = require( 'jwt-simple' );
const UUID = require( 'uuid' );
const Outputs = require( './Outputs.js' );
const config = require( '../tribes/townconf.js' );
const Checkjson = require( `./Checkjson.js`);
/*
Gestion des utilisateurs connecte
/tribes/tribeid/users/
UUID.json
/searchindex/indexTOKEN = {TOKEN:UUID}
to check authentification
indexLOGIN = {LOGIN:UUID}
to check if LOGIN exist
Used for referntial:
To update
Global: datashared/referentials/dataManagement/object/users.json
Local: data/tribe/*${header.workOn}/referentials/dataManagement/object/users.json
To use after a server rerun
data/tribe/*${header.workOn}/referentials/${header.langue}/object/users.json
Faire comme contact charger les index au lancement
et changer la logique de user/id/profil o
On initialise les objets au lancement du serveur
this.uids[u.UUID] = [u.LOGIN, u.EMAIL, u.password, u.profil, u.TOKEN];
this.logins[u.LOGIN] = u.UUID;
this.tokens[u.UUID] = u.TOKEN;
on stocke /domain/tribeid/users/logins.json et /uids.json
on stocke /domain/tribeids.json et tokkens.json
On retourne l'objet {tribeids:[list tribeid], tokens:{UUID:TOKEN}}
*/
const Pagans = {};
Pagans.init = tribeids => {
console.group( 'init Pagans logins, tokens ...' );
// store globaly tokens
const tokens = {};
const emailsglob = {};
const loginsglob = {};
// For each tribeid create series of indexes
//console.log(tribeids);
tribeids.forEach( tribeid => {
// Reset for each domain
const uids = {};
const logins = {};
const emails = {};
//check folder exist
/*if( !fs.existsSync( `${config.tribes}/${tribeid}/users` ) ) {
fs.mkdirSync( `${config.tribes}/${tribeid}/users` )
}
if( !fs.existsSync( `${config.tribes}/${tribeid}/users/searchindex` ) ) {
fs.mkdirSync( `${config.tribes}/${tribeid}/users/searchindex` )
}*/
glob.sync( `${config.tribes}/${tribeid}/users/*.json` )
.forEach( file => {
//console.log( file );
const u = fs.readJsonSync( file, 'utf-8' );
if( !u.TOKEN ) {
u.TOKEN = '';
}
//console.log( u )
uids[ u.UUID ] = [ u.LOGIN, u.EMAIL, u.PASSWORD, u.ACCESSRIGHTS, u.TOKEN ];
logins[ u.LOGIN ] = u.UUID;
loginsglob[ u.LOGIN ] = tribeid;
// On ne charge que les TOKEN valide
let decodedTOKEN = {};
if( u.TOKEN != '' ) {
try {
decodedTOKEN = jwt.decode( u.TOKEN, config.jwtSecret );
//console.log( 'decodeTOKEN', decodedTOKEN )
if( moment( decodedTOKEN.expiration ) > moment() ) {
tokens[ u.UUID ] = { TOKEN: u.TOKEN, ACCESSRIGHTS: u.ACCESSRIGHTS };
//console.log( `add token valid for ${u.UUID}:`, tokens[ u.UUID ] )
}
} catch ( err ) {
console.log( 'pb de TOKEN impossible a decoder' + u.TOKEN, err );
}
}
if( u.EMAIL ) {
emails[ u.EMAIL ] = u.UUID;
emailsglob[ u.EMAIL ] = tribeid;
}
} );
// UIDS INDEX BY DOMAIN ={UUID:[LOGIN,EMAIL,psw,accessRight,TOKEN]}
fs.outputJson( `${config.tribes}/${tribeid}/users/searchindex/uids.json`, uids, {
spaces: 2
}, err => {
if( err ) throw err;
} );
// LOGINS INDEX BY DOMAIN ={LOGIN:UUID}
fs.outputJson( `${config.tribes}/${tribeid}/users/searchindex/logins.json`, logins, {
spaces: 2
}, err => {
if( err ) throw err;
} );
// EMAILS INDEX BY DOMAIN ={EMAIL:UUID}
fs.outputJson( `${config.tribes}/${tribeid}/users/searchindex/emails.json`, emails, {
spaces: 2
}, err => {
if( err ) throw err;
} );
} );
// EMAILS et appartenance domain
fs.outputJson( `${config.tmp}/emailsglob.json`, emailsglob, {
spaces: 2
}, err => {
if( err ) throw err;
} );
// logins et appartenance domain (permet de retrouver tribeid pour un LOGIN)
fs.outputJson( `${config.tmp}/loginsglob.json`, loginsglob, {
spaces: 2
}, err => {
if( err ) throw err;
} );
// TOKENS GLOBAL INDEX Centralise tous les TOKEN pour plus de rapidité
// {UUID:TOKEN}
fs.outputJson( `${config.tmp}/tokens.json`, tokens, {
spaces: 2
}, err => {
if( err ) throw err;
} );
console.groupEnd();
return { tokens };
};
/**
* Update indexes: logins, uids and tokens
* @param {object} user User object
* @param {string} tribeid - The client identifier
* @rm {boolean} false => update, true => remove
*/
Pagans.updateDatabase = ( user, tribeid, rm = false ) => {
console.group( `Pagans.updateDatabase for ${tribeid} with user ${user.LOGIN}` )
console.assert( config.loglevel == "quiet", 'user', user );
const loginsIndex = `${config.tribes}/${tribeid}/users/searchindex/logins.json`;
fs.readJson( loginsIndex, function ( err, logins ) {
console.assert( config.loglevel == "quiet", 'logins', logins );
try {
if( rm ) {
delete logins[ user.LOGIN ];
} else {
logins[ user.LOGIN ] = user.UUID;
}
fs.outputJson( loginsIndex, logins, {
spaces: 2
}, err => {
if( err ) console.log( err );
} );
} catch ( err ) {
console.log( 'Gros pb de mise à jour Pagans.updateDatabase conflit des logins' );
}
} );
const uidsIndex = `${config.tribes}/${tribeid}/users/searchindex/uids.json`;
fs.readJson( uidsIndex, function ( err, uids ) {
try {
if( rm ) {
delete uids[ user.UUID ];
} else {
uids[ user.UUID ] = [
user.LOGIN,
user.EMAIL,
user.PASSWORD,
user.ACCESSRIGHTS,
user.TOKEN
];
}
fs.outputJson( uidsIndex, uids, {
spaces: 2
}, err => {
if( err ) console.log( err );
} );
} catch ( err ) {
console.log( 'Gros pb de mise à jour Pagans.updateDatabase conflit des uids si ce reproduit passer en mode sync bloquant' );
}
} );
const emailsIndex = `${config.tribes}/${tribeid}/users/searchindex/emails.json`;
fs.readJson( emailsIndex, function ( err, emails ) {
console.assert( config.loglevel == "quiet", 'emailss', emails );
try {
if( rm ) {
delete emails[ user.EMAIL ];
} else {
emails[ user.EMAIL ] = user.UUID;
}
fs.outputJson( emailsIndex, emails, {
spaces: 2
}, err => {
if( err ) console.log( err );
} );
} catch ( err ) {
console.log( 'Gros pb de mise à jour Pagans.updateDatabase conflit des emails' );
}
} );
const tokensIndex = `${config.tmp}/tokens.json`;
let tokens = {};
try {
tokens = fs.readJsonSync( tokensIndex );
} catch ( err ) {
console.log( 'tokens.json not available' )
}
// tokens[user.UUID] = user.TOKEN;
tokens[ user.UUID ] = { TOKEN: user.TOKEN, ACCESSRIGHTS: user.ACCESSRIGHTS };
fs.outputJsonSync( tokensIndex, tokens, {
spaces: 2
} );
/*
fs.readJson(tokensIndex, function(err, tokens) {
tokens[user.UUID] = user.TOKEN;
fs.outputJson(tokensIndex, tokens, { spaces: 2 }, err => {
if (err) console.log(err);
});
});*/
console.groupEnd();
};
/**
* Read the profil.json of an user
* @param {[type]} UUID ID of the user
* @param {[type]} tribeid tribeid
* @return {Promise} - Return a promise resolved with user data or rejected with an error
*/
// A S U P P R I M E R utiliser getinfousers pour recuperer des indexs de users
// en créer d'autres si necessaire
Pagans.getUserlist = ( header, filter, field ) => {
console.group( `getUserlist filter with filter ${filter} to get ${field}` );
/* const getuser = Pagans.getUser(header.xuuid, header.xtribeid);
if (getuser.status != 200)
return { status: getuser.status, data: getuser.payload };
const user = getuser.payload.data;
// console.log(user);
// check if update accessright allowed
// choose the level depending of ownby xuuid
let accessright = user.objectRights[header.xtribeid].users[0];
if (user.ownby.includes(header.xtribeid)) {
accessright = user.objectRights[header.xtribeid].users[1];
}
// Check update is possible at least user itself ownby itself
console.log(accessright);
console.log(accessright & 4);
if ((accessright & 4) != 4) {
return {
status: 403,
data: { info: ['forbiddenAccess'], model: 'Pagans' }
};
}
*/
const Userlist = [];
glob.sync( `${config.tribes}/${header.xworkon}/users/*/profil.json` )
.forEach( f => {
const infouser = fs.readJsonSync( f );
// Ajouter filter et liste de field
if( filter != 'all' ) {
// decode filter et test
}
const info = {};
field.split( '______' )
.forEach( k => {
if( ![ 'password' ].includes( k ) ) info[ k ] = infouser[ k ];
} );
Userlist.push( info );
} );
// console.log('userlist', Userlist);
console.groupEnd();
return {
status: 200,
data: {
data: Userlist
}
};
};
Pagans.getinfoPagans = ( tribeid, accessrights, listindex ) => {
const info = {}
const object = 'users';
const indexs = listindex.split( '_' )
let access = true;
indexs.forEach( index => {
access = !( [ 'emails', 'logins', 'uids' ].includes( index ) && !( accessrights.data[ object ] && accessrights.data[ object ].includes( 'R' ) ) );
if( access && fs.existsSync( `${config.tribes}/${tribeid}/${object}/searchindex/${index}.json` ) ) {
info[ index ] = fs.readJsonSync( `${config.tribes}/${tribeid}/${object}/searchindex/${index}.json` )
}
} )
console.log( info )
return { status: 200, data: { info: info } }
}
Pagans.getUser = ( UUID, tribeid, accessrights ) => {
console.assert( config.loglevel == "quiet", `getUser on ${UUID} for ${tribeid} with ${JSON.stringify(accessrights)}` );
if( !fs.existsSync( `${config.tribes}/${tribeid}/users/${UUID}.json` ) ) {
return {
status: 404,
data: {
info: [ 'useridNotfound' ],
model: 'Pagans',
render: {
UUID,
tribeid
}
}
}
}
const user = fs.readJsonSync( `${config.tribes}/${tribeid}/users/${UUID}.json` );
let access = true;
//console.log("test accessrights.data['users'].includes('R')", accessrights.data['users'].includes('R'))
console.assert( config.loglevel == "quiet", 'accessrights', accessrights )
access = accessrights.users && ( accessrights.users.includes( 'R' ) || ( accessrights.users.includes( 'O' ) && user.OWNEDBY.includes( UUID ) ) );
if( access ) {
return {
status: 200,
data: {
user: user,
model: "User",
info: [ "Authorizedtogetuserinfo" ]
}
};
}
return {
status: 403,
data: {
info: [ 'Forbidden' ],
model: 'Pagans',
render: {
UUID,
tribeid
}
}
};
};
Pagans.getUserIdFromEMAIL = ( tribeid, EMAIL ) => {
if( !Checkjson.test.EMAIL( EMAIL ) ) {
return {
status: 400,
data: {
info: [ 'ERREMAIL' ],
model: 'Pagans'
}
};
}
const emailsIndex = fs.readJsonSync( `${config.tribes}/${tribeid}/users/searchindex/emails.json` );
if( !emailsIndex.hasOwnProperty( EMAIL ) ) {
return {
status: 404,
data: {
info: [ 'userEMAILNotfound' ],
model: 'Pagans'
}
};
}
return emailsIndex[ EMAIL ];
};
Pagans.updateUserpassword = ( UUID, header, data ) => {
const getUser = Pagans.getUser( UUID, header.xtribeid, { users: 'W' } );
if( getUser.status == 200 ) {
const user = getUser.data.user;
// console.log('user exist', user);
const match = bcrypt.compareSync( data.password, user.PASSWORD );
if( !match ) {
return {
status: 401,
data: {
info: [ 'checkCredentials' ],
model: 'Pagans'
}
};
}
// console.log('Credentials are matching!');
if( Checkjson.test.password( {}, data.pswnew ) ) {
user.PASSWORD = bcrypt.hashSync( data.pswnew, config.saltRounds );
fs.outputJsonSync( `${config.tribes}/${header.xworkon}/users/${UUID}.json`, user, {
spaces: 2
} );
Pagans.updateDatabase( user, header.xworkon, false );
return {
status: 200,
data: {
info: [ 'successfulUpdate' ],
model: 'Pagans'
}
};
} else {
return {
status: 401,
data: {
info: [ 'pswTooSimple' ],
model: 'Pagans'
}
};
}
}
};
Pagans.createUser = ( header, data ) => {
/*
@input data={PUBKEY,EMAIL,LOGIN,UUID} check and create for header xworkon a user with generic password
*/
console.log( 'createUser on header.xworkon:' + header.xworkon + ' by user:' + header.xpaganid );
console.assert( config.loglevel == "quiet", 'with data:', data );
const ref = fs.readJsonSync( `${config.tribes}/${header.xworkon}/referentials/${header.xlang}/object/users.json` );
const logins = fs.readJsonSync( `${config.tribes}/${header.xworkon}/users/searchindex/logins.json` );
const LOGIN = Object.keys( logins );
console.assert( config.loglevel == "quiet", 'LOGIN list', LOGIN );
const emails = fs.readJsonSync( `${config.tribes}/${header.xworkon}/users/searchindex/emails.json` );
console.assert( config.loglevel == "quiet", 'emails', emails );
const EMAIL = Object.keys( emails );
console.assert( config.loglevel == "quiet", 'EMAIL list', EMAIL );
// list.UUID est forcement unique car on est en update et pas en create
if( !data.UUID ) data.UUID = UUID.v4();
// pour la logique de Checkjson il faut passer le parametre
const Checkjson = Checkjson.evaluate( {
list: {
LOGIN,
EMAIL,
UUID: []
}
}, ref, data );
console.assert( config.loglevel == "quiet", 'check & clean data before update ', check );
if( Checkjson.invalidefor.length > 0 ) {
return {
status: 403,
data: {
model: 'Pagans',
info: Checkjson.invalidefor
}
};
}
const clientConfig = fs.readJsonSync( `${config.tribes}/${header.xworkon}/clientconf.json` );
const user = Checkjson.data;
user.DATE_CREATE = new Date()
.toISOString();
user.PASSWORD = bcrypt.hashSync( clientConfig.genericpsw, config.saltRounds );
user.OWNBY = [ data.UUID ];
user.OBJECT = 'users';
// set le minimum de droit sur l'objet users dont il est le Owner
if( data.ACCESSRIGHTS ) {
user.ACCESSRIGHTS = data.ACCESSRIGHTS
} else {
user.ACCESSRIGHTS = { app: {}, data: {} };
}
user.ACCESSRIGHTS.data[ header.xworkon ] = { users: "O" };
fs.outputJsonSync( `${config.tribes}/${header.xworkon}/users/${user.UUID}.json`, user, {
spaces: 2
} );
Pagans.updateDatabase( user, header.xworkon, false );
return {
status: 200,
data: {
uuid: user.UUID,
info: [ 'successfulCreate' ],
model: 'Pagans'
}
};
};
Pagans.updateUser = ( UUID, header, data ) => {
console.log( 'updateUser UUID:' + UUID + ' on header.xworkon:' + header.xworkon + ' by user' + header.xpaganid );
// console.log('header', header);
console.assert( config.loglevel == "quiet", 'with data', data );
const getuser = Pagans.getUser( UUID, header.xworkon, { users: 'R' } );
if( getuser.status != 200 ) return {
status: getuser.status,
data: getuser.data.user
};
const user = getuser.data.user;
/*
let userconnected = user;
if (UUID != header.xuuid) {
// mean connected user want to change other user
const getuserconnected = Pagans.getUser(header.xuuid, header.xtribeid);
userconnected = getuserconnected.payload.data;
}
console.log('user to update', user);
console.log('user connected that request update', userconnected);
// check if update accessright allowed
// choose the level depending of ownby xuuid
let accessright = userconnected.objectRights[header.xworkon].users[0];
if (user.ownby.includes(header.xuuid)) {
accessright = userconnected.objectRights[header.xworkon].users[1];
}
// Check update is possible at least user itself ownby itself
console.log(accessright);
console.log(accessright & 2);
if ((accessright & 2) != 2) {
return {
status: 403,
data: { info: ['forbiddenAccess'], model: 'Pagans' }
};
}
*/
const ref = fs.readJsonSync( `${config.tribes}/${header.xworkon}/referentials/object/users_${
header.xlang
}.json` );
const logins = fs.readJsonSync( `${config.tribes}/${header.xworkon}/users/searchindex/logins.json` );
const LOGIN = Object.keys( logins )
.filter( l => logins[ l ] != user.UUID );
// console.log( 'LOGIN list', LOGIN );
const emails = fs.readJsonSync( `${config.tribes}/${header.xworkon}/users/searchindex/emails.json` );
// console.log( 'emails', emails );
const EMAIL = Object.keys( emails )
.filter( e => emails[ e ] != user.UUID );
// console.log( 'EMAIL list', EMAIL );
// list.UUID est forcement unique car on est en update et pas en create
// pour la logique de Checkjson il faut passer le parametre
const Checkjson = Checkjson.evaluate( {
profil: user[ 'apps' + header.xworkon + 'profil' ],
list: {
LOGIN,
EMAIL,
UUID: []
}
}, ref, data );
if( Checkjson.invalidefor.length > 0 ) {
return {
status: 403,
data: {
model: 'Pagans',
info: Checkjson.invalidefor,
}
};
}
data = Checkjson.data;
let saveuser = false;
let updateDatabase = false;
Object.keys( data )
.forEach( k => {
//console.log( user[ k ] )
//console.log( data[ k ] )
//console.log( '---' )
if( user[ k ] != data[ k ] ) {
user[ k ] = data[ k ];
saveuser = true;
if( [ 'TOKEN', 'LOGIN', 'EMAIL' ].includes( k ) ) updateDatabase = true;
// attention si LOGIN ou EMAIL change il faut checker qu il n existe pas dejà risque de conflit
}
} );
if( saveuser ) {
//console.log( 'mise à jour user profile.json' );
if( data.TOKEN ) {
user.date_lastLOGIN = new Date()
.toISOString();
} else {
user.date_update = new Date()
.toISOString();
}
try {
fs.outputJsonSync( `${config.tribes}/${header.xworkon}/users/${UUID}.json`, user, {
spaces: 2
} );
//console.log( 'declenche updatabase', updateDatabase )
if( updateDatabase ) {
// mean index have to be updated
Pagans.updateDatabase( user, header.xworkon, false );
console.assert( config.loglevel == "quiet", 'MISE A JOUR DU TOKEN ou de l\'EMAIL ou du LOGIN' );
}
} catch ( err ) {
console.log( 'ERRRRR need to understand update impossible of user: ' + UUID + ' in domain:' + header.xworkon + ' from user ' + header.xpaganid + ' of domain:' + header.xtribe );
console.log( 'with data :', data );
return {
status: 400,
data: {
info: [ 'failtoWritefs' ],
model: 'Pagans'
}
};
}
}
return {
status: 200,
data: {
info: [ 'successfulUpdate' ],
model: 'Pagans'
}
};
};
Pagans.deleteUser = ( UUID, header ) => {
// Delete remove from users object UUID and update index
// Activity is not deleted => means some activity can concern an UUID that does not exist anymore.
// update index
const infouser = fs.readJsonSync( `${config.tribes}/${header.xworkon}/users/${UUID}.json` );
Pagans.updateDatabase( infouser, header.xworkon, true );
fs.removeSync( `${config.tribes}/${header.xworkon}/users/${UUID}.json` );
return {
status: 200,
data: {
info: [ 'successfulDelete' ],
modedl: 'Pagans'
}
};
};
/*
@header { xtribeid: client domain name data
A VERIFIER inutile ,xworkon: client domain name where user is store and where data are stored
,xuuid: 1 if unknown else if user id auhtneticated
,xlanguage: langue used fr en return referential in this lang
,xauth: TOKEN valid for 24h'}
workon=xtribeid in an app client usage
in case of xtribeid=mymaidigit,
if workon==mymaildigit => admin role on any xworkon
else adlin role only in xworkon specified
@body {LOGIN: password:}
return {status:200, data:{data:{TOKEN,UUID}}}
return {status:401,data:{info:[code list], model: referential}}
*/
Pagans.loginUser = ( header, body, checkpsw ) => {
// On recupere tribeid du LOGIN
// ATTENTION xworkon peut être different du user xtribeid
//(cas d'un user qui a des droits sur un autre domain et qui travail sur cet autre domain)
// les function Pagans utilise le domain de travail xWorkon
// il faut donc modifier le header au moment du LOGIN
// pour que l'update du user au moment du LOGIN concerne bien le bon domain
header.xworkon = header.xtribe
const LOGINdom = fs.readJsonSync( `${config.tmp}/loginsglob.json` );
console.assert( config.loglevel == "quiet", LOGINdom )
console.assert( config.loglevel == "quiet", body )
if( !LOGINdom[ body.LOGIN ] ) {
return {
status: 401,
data: { info: [ 'LoginDoesNotExist' ], model: 'Pagans' }
};
}
const logins = fs.readJsonSync( `${config.tribes}/${LOGINdom[body.LOGIN]}/users/searchindex/logins.json` );
if( !Object.keys( logins )
.includes( body.LOGIN ) ) {
return {
status: 401,
data: {
info: [ 'LOGINDoesNotExist' ],
model: 'Pagans',
moreinfo: `Le login ${body.LOGIN} does not exist for tribeid ${LOGINdom[body.LOGIN]}`
}
};
}
// Load user
const uid = logins[ body.LOGIN ];
const getUser = Pagans.getUser( uid, LOGINdom[ body.LOGIN ], { users: 'R' } );
console.log( 'getPagans', getUser )
if( getUser.status != 200 ) {
return { status: 200, data: { model: 'Pagans', user: getUser.data.user } };
}
const user = getUser.data.user;
console.log( 'user', user )
if( checkpsw ) {
const match = bcrypt.compareSync( body.PASSWORD, user.PASSWORD );
if( !match ) {
return {
status: 401,
data: {
info: [ 'checkCredentials' ],
model: 'Pagans'
}
};
}
}
// Mise à jour user pour app LOGIN
user.tribeid = LOGINdom[ body.LOGIN ]
user.TOKEN = jwt.encode( {
expiration: moment()
.add( 1, 'day' ),
UUID: user.UUID
}, config.jwtSecret );
// on met à jour le header qui authentifie le user connecte
header.xtribe = LOGINdom[ body.LOGIN ]
header.xpaganid = user.UUID;
header.xauth = user.TOKEN;
// On modifie xworkon car au LOGIN on est forcemenet identifiable sur tribeid
// xworkon est utiliser pour travailler sur un environnement client different de celui
// de l'appartenace du user
header.xworkon = LOGINdom[ body.LOGIN ];
const majuser = Pagans.updateUser( user.UUID, header, {
UUID: user.UUID,
TOKEN: user.TOKEN
} );
// Enleve info confidentiel
delete user.PASSWORD;
if( user.ACCESSRIGHTS.data[ "Alltribeid" ] ) {
//cas admin on transforme les droits sur tous les tribeid existant
const newaccessrightsdata = {}
fs.readJsonSync( `${config.tribes}/tribeids.json` )
.forEach( cid => {
newaccessrightsdata[ cid ] = user.ACCESSRIGHTS.data[ "Alltribeid" ]
} )
user.ACCESSRIGHTS.data = newaccessrightsdata;
}
// on recupere le menu de l app qui demande le LOGIN si existe dans user.ACCESSRIGHTS.app[]
// header['X-app'] = tribeid:Projet pour récuperer le menu correspondant
console.assert( config.loglevel == "quiet", "header.xapp", header.xapp )
console.assert( config.loglevel == "quiet", "user.ACCESSRIGHTS.app[header.xapp]", user.ACCESSRIGHTS.app[ header.xapp ] );
return {
status: 200,
data: {
model: "Pagans",
info: [ 'loginSuccess' ],
user: user
}
};
};
Pagans.getlinkwithoutpsw = async ( EMAIL, header ) => {
// check le domain d'appartenance de l'eamail dans /tribes/emailsglob.json={email:cleintId}
// on remplace le header.xtribeid
const domforemail = fs.readJsonSync( `${config.tribes}/emailsglob.json`, 'utf-8' );
if( domforemail[ EMAIL ] ) {
header.xtribe = domforemail[ EMAIL ]
} else {
return { status: 404, info: { model: 'Pagans', info: [ 'emailnotfound' ], moreinfo: "email does not exist in /emailsglob.json" } };
}
// recupere le uuid du user dans /tribes/tribeid/users/searchindex/emails.json
// puis l'ensemble des info des user du domain /uuids.json
// infoforuuid[uuidforemail[EMAIL]] permet de récupérer toutes info du user, droit, etc...
const uuidforemail = fs.readJsonSync( `${config.tribes}/${header.xtribe}/users/searchindex/emails.json`, 'utf8' );
const infoforuuid = fs.readJsonSync( `${config.tribes}/${header.xtribe}/users/searchindex/uids.json`, 'utf8' );
// On recupere le modele d'email appemailinfo qui doit être présent dans clientconf.json
let confdom = fs.readJsonSync( `${config.tribes}/${header.xtribe}/clientconf.json`, 'utf8' );
let checkinfomail = "";
if( !confdom.appemailinfo ) {
checkinfomail += ' Erreur de clientconfig il manque un objet appemailinfo pour poursuivre';
}
if( checkinfomail != "" ) {
console.log( `Pb de config pour ${header.xtribe} ${checkinfomail} ` )
return {
status: 500,
info: {
model: 'Pagans',
info: [ 'objectmissingclientconf' ],
moreinfo: checkinfomail
}
};
}
let simulelogin;
try {
simulelogin = await Pagans.loginUser( header, {
LOGIN: infoforuuid[ uuidforemail[ EMAIL ] ][ 0 ],
PASSWORD: ""
}, false );
console.log( 'info simulelogin', simulelogin )
} catch ( err ) {
return {
status: 501,
info: {
model: 'Pagans',
info: [ 'loginImpossible' ],
moreinfo: "Impossible de se loger avec " + infoforuuid[ uuidforemail[ EMAIL ] ][ 0 ]
}
};
}
const url = `${config.rootURL}?xauth=${simulelogin.data.TOKEN}&xuuid=${simulelogin.data.UUID}&xtribeid=${simulelogin.data.tribeid}&xworkOn=${header.xworkon}&xlang=${header.xlang}`
//console.log('envoi email avec' + url)
confdom.appemailinfo.msg.destperso = [ {} ];
confdom.appemailinfo.msg.destperso[ 0 ].email = EMAIL;
confdom.appemailinfo.msg.destperso[ 0 ].subject = "Lien de réinitialisation valable 1h"
confdom.appemailinfo.msg.destperso[ 0 ].titre = "Vous avez oublier votre mot de passe"
confdom.appemailinfo.msg.destperso[ 0 ].texte = `
<p style='color: #999999; font-size: 16px; line-height: 24px; margin: 0;text-align:justify;'>
Bonjour,<br> Vous nous avez signalé que vous avez oublié votre mot de passe pour cette email.
Avec le lien suivant vous allez pouvoir utiliser votre interface 1h maximum.
<a href="${url}">Clicker ICI</a>.<br>
Nous vous conseillons de changer votre mot de passe.</p>
`
//console.log('envoi header :', header);
Outputs.sendMailcampain( confdom.appemailinfo.msg, header );
console.log( confdom.appemailinfo );
return {
status: 200,
info: {
model: 'Pagans',
info: [ 'emailsentforReinit' ],
moreinfo: 'EMAIL sent with unique link ' + url
}
};
}
module.exports = Pagans;

View File

@ -1,416 +0,0 @@
const glob = require( 'glob' );
const path = require( 'path' );
const fs = require( 'fs-extra' );
const config = require( '../tribes/townconf.js' );
const Referentials = {};
/*
Manage Referential object data
each object is compose of a list of fields
each fields have it owns structur and check
those common rules allow to be used to manage:
- forms (creation to collect data)
- data check
- data access rights
common referential data stored in /data/shared/referential/
*/
Referentials.clientconf = ( xworkOn, listkey ) => {
/*
Retourne les info d'un clientconf.json sur une liste de [cle]
*/
let conf = {};
let dataconf = {};
//console.log( `${config.tribes}/${xworkOn}/clientconf.json` )
try {
conf = fs.readJsonSync( `${config.tribes}/${xworkOn}/clientconf.json` );
// remove information notrelevant for
[ 'emailFrom', 'emailClient', 'emailCc', 'commentkey', 'clezoomprivate', 'stripekeyprivate', 'genericpsw' ].forEach( c => {
delete conf[ c ];
} );
listkey.forEach( k => dataconf[ k ] = conf[ k ] )
//console.log( 'dataconf', dataconf )
} catch ( err ) {
console.log( 'Attention demande sur clienId inconnu ' + xworkOn );
}
return {
status: 200,
payload: {
data: dataconf
}
};
};
Referentials.clientconfglob = () => ( {
status: 200,
payload: {
data: fs.readJsonSync( `${config.tmp}/clientconfglob.json` )
}
} );
Referentials.getref = ( origin, source, ref, xworkOn, xlang ) => {
// If request origin then send back referential with all language in it
// if not origin or json source return by language
let referent = {};
let src;
if( origin && [ 'object', 'data' ].includes( source ) ) {
src = `${config.tribes}/${xworkOn}/referentials/${source}/${ref}.json`
} else {
src = `${config.tribes}/${xworkOn}/referentials/${source}/${ref}_${xlang}.json`;
}
//console.log( src )
try {
referent = fs.readJsonSync( src );
} catch ( err ) {
console.log( `Request ${src} does not exist ` );
}
return {
status: 200,
payload: {
data: referent
}
};
};
Referentials.putref = ( source, name, xworkOn, data ) => {
/*
We get a referential, we have 3 kinds of sources:
* data = [{uuid,DESC:{fr:,en,},DESCLONG:{fr:,en:}, other field}]
only DESC and DESCLONG have a translation
* json = are full complex object in language name_lg.json
* object = [{uuid,DESC:{fr,en},DESCLONG:{fr,en}},tpl,}]
Difference between data and object is that object defines rule to manage an object, and how to create a forms to get data each data is saved in one folder object/uuid.json and have to respect the corresponding object referentials definition.
For data and object it is possible only to put a file with all language available.
When store this script erase with the new file per _lg
name for source=json must end by _lg
*/
//console.log( data )
const pat = /.*_..\.json$/;
const file = `${config.tribes}/${xworkOn}/referentials/${source}/${name}.json`
if( [ 'object', 'data' ].includes( source ) ) {
if( pat.test( name ) ) {
return { status: 404, payload: { model: 'Referentials', info: [ 'nameunconsistent' ], moreinfo: "can not be update with one lang need a full file with language for object or data" } }
} else {
fs.outputJsonSync( file, data );
return Refernetials.update( xworkOn, source, name )
}
} else {
if( !pat.test( name ) ) {
return { status: 404, payload: { model: 'Referentials', info: [ 'nameunconsistent' ], moreinfo: "can not be update without a lang _lg.json a referential json" } }
} else {
fs.outputJsonSync( file, data );
return { status: 200, payload: { model: 'Referentials', info: [ 'successfull' ], moreinfo: "ref json updated " } }
}
};
};
Referentials.updatefull = ( tribeid ) => {
let err = "";
let nbrefupdate = 0;
const pat = /.*_..\.json$/;
[ 'object', 'data' ].forEach( o => {
glob.sync( `${config.tribes}/${tribeid}/referentials/${o}/*.json` )
.forEach( f => {
if( !pat.test( f ) ) {
const res = Referentials.update( tribeid, o, path.basename( f, '.json' ) );
if( res.status != 200 ) {
err += `Error on ${o}/${path.basename(f)}`
} else {
nbrefupdate += 1;
}
}
} )
} );
if( err != "" ) {
return { status: 500, payload: { info: [ 'Errupdateref' ], model: "Referentials", moreinfo: err } }
}
return { status: 200, payload: { info: [ 'Success' ], model: "Referentials", moreinfo: `Number of object and data ref updated: ${nbrefupdate}` } }
};
Referentials.inittribeid = () => {
console.log( "Clientconf list for this server", `${config.tribes}/**/clientconf.json` );
const TribesGlobalConfig = glob.sync( `${config.tribes}/**/clientconf.json` )
.map( f => fs.readJsonSync( f ) );
// store global conf for sharing to other api
fs.outputJsonSync( `${config.tmp}/clientconfglob.json`, TribesGlobalConfig, {
spaces: 2
} );
return { status: 200, payload: { moreinfo: TribesGlobalConfig } }
}
Referentials.generetribeids = () => {
const tribeids = [];
fs.readJsonSync( `${config.tmp}/clientconfglob.json` )
.forEach( c => {
if( !tribeids.includes( c.tribeid ) ) tribeids.push( c.tribeid );
} );
fs.outputJsonSync( `${config.tmp}/tribeids.json`, tribeids );
console.log( `update ${config.tribes}/tribeids` );
return tribeids;
}
Referentials.genereallowedDOM = () => {
const confglob = fs.readJsonSync( `${config.tmp}/clientconfglob.json` );
let allDom = [];
confglob.forEach( c => {
c.allowedDOMs.forEach( d => {
if( !allDom.includes( d ) ) allDom = allDom.concat( d );
} )
} );
return allDom;
};
/* A voir si encore necessaire pour générer un environnement identique
sur un autre server
// Génére les domaines s'ils n'existe pas dans le repertoire
function genereEnvClient() {
const confglob = fs.readJsonSync(
`${config.sharedData}/clientconfglob.json`
);
confglob.forEach(function(c) {
config.tribeidsConf[c.tribeid] = c;
if (c.allowedURLs) {
c.allowedURLs.forEach(u => {
if (!config.allowedURLs.includes(u)) {
config.allowedURLs.push(u);
}
});
} else {
console.log('erreur de fichier config d\'un site pour ', c);
}
// GLOBAL Tribes IDS INDEX
maketribeidsIndex();
if (!fs.existsSync(`${config.tribes}/${c.tribeid}`)) {
const execSync = require('child_process').execSync;
execSync(`cp -r ${config.tribes}/modele ${config.tribes}/${c.tribeid}`);
}
});
}
*/
Referentials.update = ( tribeid, source, name ) => {
/*
Replace for each language the referential name for a tribeid
After each update the version number is incremented by 1 in clientconf.json
*/
if( !fs.existsSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}.json` ) ) {
return { status: 500, payload: { info: [ "unknownRef" ], model: "Referentials", moreinfo: `file does not exist ${config.tribes}/${tribeid}/referentials/${source}/${name}.json` } }
};
const clientconf = fs.readJsonSync( `${config.tribes}/${tribeid}/clientconf.json` );
if( !clientconf.langueReferential ) {
return { status: 500, payload: { info: [ "missingConf" ], model: "Referentials", moreinfo: ` ${config.tribes}/${tribeid}/clientconf.json does not contain langueReferential array` } }
}
const ref = fs.readJsonSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}.json` );
clientconf.langueReferential.forEach( lg => {
//manage translation
let refnew = [];
refnew = [];
ref.forEach( d => {
if( d.DESC ) d.DESC = d.DESC[ lg ];
if( d.DESCLONG ) d.DESCLONG = d.DESCLONG[ lg ];
if( d.INFO ) d.INFO = d.INFO[ lg ];
if( d.desc ) d.desc = d.desc[ lg ];
if( d.desclong ) d.desclong = d.desclong[ lg ];
if( d.info ) d.info = d.info[ lg ];
if( d.placeholder ) d.placeholder = d.placeholder[ lg ];
refnew.push( d )
} )
//save new ref in language
//console.log( "New ref", refnew )
console.log( `Update referentials per lg ${config.tribes}/${tribeid}/referentials/${source}/${name}_${lg}.json` )
fs.outputJsonSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}_${lg}.json`, refnew, {
spaces: 2
} );
} );
//upgrade version number
if( !clientconf.referentials ) clientconf.referentials = {};
if( !clientconf.referentials[ source ] ) clientconf.referentials[ source ] = {};
if( !clientconf.referentials[ source ][ name ] ) clientconf.referentials[ source ][ name ] = { version: 0 };
clientconf.referentials[ source ][ name ].version += 1;
fs.outputJsonSync( `${config.tribes}/${tribeid}/clientconf.json`, clientconf, 'utf8' );
return {
status: 200,
payload: {
info: [ 'successUpdate' ],
model: "Referentials",
moreinfo: `${name} updated`
}
}
};
//console.log( Referentials.update( 'apxtrib', "object", "user" ) )
Referentials.genereobjet = ( tribeid, destination, tplmustache, objet, filtre ) => {
/* @TODO
Genere des objets d'agregat
@tribeid = data/tribee/ identifiant client
@destinations = [] of destination
@tplmustache = fichier mustache de mise en page
@objet = nom d'objet contact, companies, items, users
@filtre = fonction a executer
*/
}
//////// EN DESSOUS DE CETTE LIGNE A SUPPRIMER
/*
Le principe consistait à partager des referentiels dans shareddataLa gestion est trop compliqué => le principe chaque client duplique un referentiel pour que les app qui s'appuie sur des composants communs puissent fonctionner
*/
/*Referentials.genereClientObjectASUPP = () => {
const confglob = fs.readJsonSync( `${config.tmp}/clientconfglob.json` );
// Check and update folder and data per lang
// c as tribeid
confglob.forEach( ( c, postribeid ) => {
//check folder are well create
const lstfolder = [ 'actions', 'actions/done', 'actions/todo', 'cards', 'logs', 'orders', 'orders/reservation', 'orders/purchase', 'orders/contact', 'public', 'public/reservation', 'tags', 'tags/stats', 'tags/archives', 'tags/hits', 'tags/imgtg', 'users' ];
lstfolder.forEach( fol => {
if( !fs.existsSync( `${config.tribes}/${c.tribeid}/${fol}` ) ) {
fs.mkdirSync( `${config.tribes}/${c.tribeid}/${fol}` );
}
} )
if( c.referentials && !c.langue ) { console.log( `ERREUR referentials mais pas de langue:[] pour ${c.tribeid}/clientconf.json` ) }
if( c.referentials && c.langue ) {
let majclientconf = false;
// Create and check Object structure
Object.keys( c.referentials.object )
.forEach( o => {
// if object exist in shared then it merge sharedObject and domain referential object
let objfull = [];
const objshared = `${config.sharedData}/referentials/dataManagement/object/${o}.json`;
if( fs.existsSync( objshared ) ) {
objfull = objfull.concat( fs.readJsonSync( objshared ) );
}
const objdomain = `${config.tribes}/${c.tribeid}/referentials/dataManagement/object/${o}.json`;
if( fs.existsSync( objdomain ) ) {
objfull = objfull.concat( fs.readJsonSync( objdomain ) );
}
c.langue.forEach( lg => {
const objfulllg = objfull.map( field => {
if( field.DESC ) field.DESC = field.DESC[ lg ];
if( field.DESCLONG ) field.DESCLONG = field.DESCLONG[ lg ];
return field;
} );
const objectdomlg = `${config.tribes}/${c.tribeid}/referentials/${lg}/object/${o}.json`;
let savedObject = {};
if( fs.existsSync( objectdomlg ) ) {
savedObject = fs.readJsonSync( objectdomlg );
}
// TODO Always true change later to update only if needded
if( !fs.existsSync( objectdomlg ) || objfulllg.length !== savedObject.length || 1 == 1 ) {
fs.outputJsonSync( objectdomlg, objfulllg, {
spaces: 2
} );
confglob[ postribeid ].referentials.object[ o ].version += 1;
majclientconf = true;
}
} );
} );
// datafile
Object.keys( c.referentials.data )
.forEach( d => {
// if object exist in shared then it merge sharedObject and domain referential object
// console.log(c.tribeid + '--' + d);
let datafull = [];
const datashared = `${
config.sharedData
}/referentials/dataManagement/data/${d}.json`;
if( fs.existsSync( datashared ) ) {
datafull = datafull.concat( fs.readJsonSync( datashared ) );
}
const datadomain = `${config.tribes}/${
c.tribeid
}/referentials/dataManagement/data/${d}.json`;
if( fs.existsSync( datadomain ) ) {
datafull = datafull.concat( fs.readJsonSync( datadomain ) );
}
/* const defdata = `${config.tribes}/${
c.tribeid
}/referentials/dataManagement/data/${d}.json`;
*/
// for each Langues => generate fr.obj and compare it with existing file
// if diff then => upgrade version number in clientconf
// console.log(datafull);
// this could be improved by usind d.meta wich is the object that DESCribe this data
/* c.langue.forEach( lg => {
let meta;
if( c.referentials.data[ d ].meta ) {
meta = fs.readJsonSync( `${config.tribes}/${c.tribeid}/referentials/${lg}/object/${
c.referentials.data[d].meta
}.json` );
}
let datalg;
const datafulllg = datafull.map( tup => {
datalg = {};
meta.forEach( ch => {
if( tup[ ch.idfield ] ) {
if( ch.multilangue ) {
datalg[ ch.idfield ] = tup[ ch.idfield ][ lg ];
} else {
datalg[ ch.idfield ] = tup[ ch.idfield ];
}
}
} );
return datalg;
} );
// lit le fichier correspondant et le compare si différent le sauvegarde
// stocke l'information d'upgrade d ela version
const datadomlg = `${config.tribes}/${
c.tribeid
}/referentials/${lg}/data/${d}.json`;
let saveddata = {};
if( fs.existsSync( datadomlg ) ) {
saveddata = fs.readJsonSync( datadomlg );
}
// Condition to improve
// TODO always change file to improvelater by detecting real change.
if( !fs.existsSync( datadomlg ) || datafulllg.length != saveddata.length || 1 == 1 ) {
fs.outputJsonSync( datadomlg, datafulllg, {
spaces: 2
} );
confglob[ postribeid ].referentials.data[ d ].version += 1;
majclientconf = true;
}
} );
} );
// json file that have to start with lg {lg:'':{json }}
Object.keys( c.referentials.json )
.forEach( j => {
// if object exist in shared then it merge sharedObject and domain referential object
// console.log(c.tribeid + '--' + d);
let jsonfull = [];
const jsondomain = `${config.tribes}/${c.tribeid}/referentials/dataManagement/json/${j}.json`;
if( fs.existsSync( jsondomain ) ) {
jsonfull = fs.readJsonSync( jsondomain );
}
c.langue.forEach( lg => {
const jsondomlg = `${config.tribes}/${
c.tribeid
}/referentials/${lg}/json/${j}.json`;
// console.log('jsondomlg', jsondomlg);
let datalg = jsonfull;
if( jsonfull[ lg ] ) {
datalg = jsonfull[ lg ];
}
fs.outputJsonSync( jsondomlg, datalg, {
spaces: 2
} );
} );
} );
// update clientconf domain with updated version
if( majclientconf ) {
fs.outputJsonSync( `${config.tribes}/${c.tribeid}/clientconf.json`, c, {
spaces: 2
} );
}
}
} );
// update global conf
fs.outputJsonSync( `${config.tmp}/clientconfglob.json`, confglob, {
spaces: 2
} );
};*/
module.exports = Referentials;

View File

@ -1,220 +0,0 @@
const glob = require( 'glob' );
const path = require( 'path' );
const fs = require( 'fs-extra' );
// Check if package is installed or not to pickup the right config file
const config = require( '../tribes/townconf.js' );
const Referentials = {};
/*
Manage Referential object data
each object is compose of a list of fields
each fields have it owns structur and check
those common rules allow to be used to manage:
- forms (creation to collect data)
- data check
- data access rights
common referential data stored in /data/shared/referential/
*/
Referentials.clientconf = ( xworkOn, listkey ) => {
/*
Retourne les info d'un clientconf.json sur une liste de [cle]
*/
let conf = {};
let dataconf = {};
console.log( `${config.tribes}/${xworkOn}/clientconf.json` )
try {
conf = fs.readJsonSync( `${config.tribes}/${xworkOn}/clientconf.json` );
// remove information notrelevant for
[ 'emailFrom', 'emailClient', 'emailCc', 'commentkey', 'clezoomprivate', 'stripekeyprivate', 'genericpsw' ].forEach( c => {
delete conf[ c ];
} );
listkey.forEach( k => dataconf[ k ] = conf[ k ] )
console.log( 'dataconf', dataconf )
} catch ( err ) {
console.log( 'Attention demande sur clienId inconnu ' + xworkOn );
}
return {
status: 200,
payload: {
data: dataconf
}
};
};
Referentials.clientconfglob = () => ( {
status: 200,
payload: {
data: fs.readJsonSync( `${config.tmp}/clientconfglob.json` )
}
} );
Referentials.inittribeid = () => {
console.log( "Clientconf list for this server", `${config.tribes}/**/clientconf.json` );
const TribesGlobalConfig = glob.sync( `${config.tribes}/**/clientconf.json` )
.map( f => fs.readJsonSync( f ) );
// store global conf for sharing to other api
fs.outputJsonSync( `${config.tmp}/clientconfglob.json`, TribesGlobalConfig, {
spaces: 2
} );
return { status: 200, payload: { moreinfo: TribesGlobalConfig } }
}
Referentials.generetribeids = () => {
const tribeids = [];
fs.readJsonSync( `${config.tmp}/clientconfglob.json` )
.forEach( c => {
if( !tribeids.includes( c.tribeid ) ) tribeids.push( c.tribeid );
} );
fs.outputJsonSync( `${config.tmp}/tribeids.json`, tribeids );
console.log( `update ${config.tribes}/tribeids` );
return tribeids;
}
Referentials.genereallowedDOM = () => {
const confglob = fs.readJsonSync( `${config.tmp}/clientconfglob.json` );
let allDom = [];
confglob.forEach( c => {
c.allowedDOMs.forEach( d => {
if( !allDom.includes( d ) ) allDom = allDom.concat( d );
} )
} );
return allDom;
};
Referentials.getref = ( source, ref, xworkOn, xlang, singlelang = true ) => {
let referent = {};
let src = `${config.tribes}/${xworkOn}/referentials/${xlang}/${source}/${ref}.json`;
if( !singlelang ) {
//request full referential to manage
src = `${config.tribes}/${xworkOn}/referentials/dataManagement/${source}/${ref}.json`
}
console.log( src )
try {
referent = fs.readJsonSync( src );
} catch ( err ) {
console.log( `Attention demande de referentiel inexistant pour ${src} ` );
}
return {
status: 200,
payload: {
data: referent
}
};
};
Referentials.putref = ( source, name, xworkOn, data ) => {
/*
We get a referential, we have 3 kinds of sources:
* data = [{uuid,desc:{fr:,en,},desclong:{fr:,en:}, other field}]
only desc and desclong have a translation
* json = {"fr":{},"en":{}, ...} are full complex object in language
* object = [{uuid,desc:{fr,en},desclong:{fr,en}},tpl,}]
Difference between data and object is that object defines rule to manage an object, and how to create a forms to get data each data is saved in one folder object/uuid.json and have to respect the corresponding object referentials definition.
*/
console.log( data )
// Create a backup of the day hour if exist
const file = `${config.tribes}/${xworkOn}/referentials/dataManagement/${source}/${name}.json`
if( fs.existsSync( file ) ) {
//backup change done per hour
const origin = fs.readJsonSync( file, 'utf-8' )
fs.outputJsonSync( `${config.tribes}/${xworkOn}/referentials/dataManagementBackup/${source}/${name}${moment().format('YYYYMMDDHHmm')}.json`, origin, { spaces: 2 } )
} else {
console.log( `Referential ${name}.json does not exist this created it` )
}
console.log( 'ref backup before update', name );
fs.outputJsonSync( file, data, { spaces: 2 } );
// update/create new referential and new version
return Referentials.update( xworkOn, source, name );
};
Referentials.updatefull = ( tribeid ) => {
// source json are only per lg so no full update for json
let err = "";
[ 'object', 'data' ].forEach( o => {
glob.sync( `${config.tribes}/${tribeid}/referentials/dataManagement/${o}/*.json` )
.forEach( f => {
if( finipaspar_lg ) {
const res = Referentials.update( tribeid, o, path.basename( f, '.json' ) );
if( res.status != 200 ) {
err += `Error on ${o}/${path.basename(f)}`
}
}
} )
} );
if( err != "" ) {
return { status: 500, payload: { info: [ 'Errupdateref' ], model: "Referentials", moreinfo: err } }
}
return { status: 200, payload: { info: [ 'Success' ], model: "Referentials" } }
};
Referentials.update = ( tribeid, source, name ) => {
/*
Replace for each language the referential name for a tribeid
After each update the version number is incremented by 1 in clientconf.json
*/
if( !fs.existsSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}.json` ) ) {
return { status: 500, payload: { info: [ "unknownRef" ], model: "Referentials", moreinfo: `file does not exist ${config.tribes}/${tribeid}/referentials/${source}/${name}.json` } }
};
const clientconf = fs.readJsonSync( `${config.tribes}/${tribeid}/clientconf.json` );
if( !clientconf.langueReferential ) {
return { status: 500, payload: { info: [ "missingConf" ], model: "Referentials", moreinfo: ` ${config.tribes}/${tribeid}/clientconf.json does not contain langueReferential array` } }
}
const ref = fs.readJsonSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}.json` );
clientconf.langueReferential.forEach( lg => {
/*if( !fs.existsSync( `${config.tribes}/${tribeid}/referentials/${lg}` ) ) {
[ '', '/data', '/json', '/object' ].forEach( p => {
fs.mkdirSync( `${config.tribes}/${tribeid}/referentials/${lg}${p}` );
} )
}
*/
//manage translation
let refnew = [];
if( source == 'json' ) {
refnew = ref[ lg ]
} else {
refnew = [];
ref.forEach( d => {
if( d.desc ) d.desc = d.desc[ lg ];
if( d.desclong ) d.desclong = d.desclong[ lg ];
if( d.info ) d.info = d.info[ lg ];
if( d.placeholder ) d.placeholder = d.placeholder[ lg ];
refnew.push( d )
} )
}
//save new ref in language
console.log( "testtttt", refnew )
console.log( `${config.tribes}/${tribeid}/referentials/${source}/${name}_${lg}.json` )
fs.outputJsonSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}_${lg}.json`, refnew, {
spaces: 2
} );
} );
//upgrade version number
if( !clientconf.referentials[ source ][ name ] ) clientconf.referentials[ source ][ name ] = { version: 0 };
clientconf.referentials[ source ][ name ].version += 1;
return {
status: 200,
payload: {
info: [ 'successUpdate' ],
model: "Referentials",
moreinfo: `${name} updated`
}
}
};
//console.log( Referentials.update( 'apxtrib', "object", "user" ) )
Referentials.genereobjet = ( tribeid, destination, tplmustache, objet, filtre ) => {
/* @TODO
Genere des objets d'agregat
@tribeid = data/tribee/ identifiant client
@destinations = [] of destination
@tplmustache = fichier mustache de mise en page
@objet = nom d'objet contact, companies, items, users
@filtre = fonction a executer
*/
}
module.exports = Referentials;

View File

@ -1,174 +0,0 @@
const fs = require( 'fs-extra' );
const path = require( 'path' );
const dnsSync = require( 'dns-sync' );
const Mustache = require( 'mustache' );
const Nations = require('./Nations.js')
const Setup = {};
const nationsync = Nations.updateChains()
if (nationsync.status!=200){
console.log( '\x1b[31m Check your internet access, to setup this town we need to update the Nations. It seems we cannot do it' );
process.exit();
}
if( !fs.existsSync( '/etc/nginx/nginx.conf' ) ) {
console.log( '\x1b[31m Check documentation, nginx have to be installed on this server first, no /etc/nginx/nginx.conf available' );
process.exit();
}
if( !fs.existsSync( './nationchains/tribes/index/conf.json' ) ){
console.log( `\x1b[42m####################################\nWellcome into apxtrib, this is a first install.\nWe need to make this server accessible from internet subdomain.domain to current IP. This setup will create your unique tribeid, with an admin login user to let you connect to the parameter interface.\nCheck README's project to learn more. more.\n#####################################\x1b[0m` );
const townSetup = fs.readJsonSync( './app/setup/townSetup.json') ;
console.log( `Current setup conf from :./app/setup/townSetup.json\nChange with relevant setup data and rerun yarn setup` ) ;
console.log( townSetup )
const readline = require( 'readline' );
const rl = readline.createInterface( {
input: process.stdin,
output: process.stdout
} );
rl.question( 'This is the data from ./app/setup/townSetup.json used, is it correct to use as first install (Yes/no)?', function ( rep1 ) {
let quest = `This is a production install, please check that ${townSetup.townName}.${townSetup.nationName}.${townSetup.dns} IP is well redirect to tour server`;
if( rep1 !== "Yes" ) process.exit( 0 );
if( townSetup.dns == 'unchain' ) {
quest = `This is a development installation, please add in your /etc/hosts 127.0.0.1 ${townSetup.townName}.${townSetup.nationName}.${townSetup.dns} `;
}
rl.question( quest + '\nAre you sure to set this? (Yes/no)', function ( rep2 ) {
if( rep2 == "Yes" ) {
const Checkjson = Setup.check( townSetup );
if( Checkjson == "" ) {
const townconf=fs.readJsonSync('./app/setup/townconf.json')
// create tribes folder with townconf.json
const towndata={...townSetup,...townconf};
const Towns = require('./Towns');
const Tribes = require('./Tribes');
const Pagans = require('./Pagans');
if (!towndata.mayorid ) Pagans.create
Towns.create('./nationchains','./nationchains','towns',{...townSetup,...townconf});
//Nationschains.create(townSetup);
Tribes.create(townSetup);
// creer un lien symbolique vers /nationchains/ pour traiter les demandes via xworkon comme une tribe
//Setup.config( townSetup );
} else {
console.log( check );
}
} else {
console.log( 'Nothing done please, check setup/configsetup.json and answer twice Yes' )
}
rl.close();
} );
} );
rl.on( 'close', function () {
console.log( '\n Setup process ended' );
process.exit( 0 );
} );
} else {
console.log( 'Carefull you have already a config.js that is running. If you want to change remove config.js file and run again yarn setup' );
}
Setup.Checkjson = conf => {
var rep = "";
const nation_town=fs.readJsonSync('./nationchains/socialworld/objects/towns/searchindex/towns_nation_uuid.json');
if (!ObjectKeys(nation_town).includes(conf.nationName)){
rep+=`your nationName ${conf.nationName} does not exist you have to choose an existing one`;
}
if (nation_town[conf.nationName].includes(conf.townName)){
rep+=`This conf.townName already exist you have to find a unique town name per nation`;
}
const getnation = Odmdb.get('./nationchains/socialworld/objects','towns',[conf.NationName],[nationId])
//if getnation.data.notfound
conf.language.forEach( l => {
if( ![ "fr", "en", "it", "de", "sp" ].includes( l ) ) {
rep += l + " Only fr,en,it,de,sp are available \n";
}
} );
if( !fs.existsSync( `/home/${conf.sudoerUser}` ) ) {
rep += `/home/${conf.sudoerUser} does not exist, user has to be create with a /home on this server\n`;
}
try {
if ("true"== execSync("timeout 2 sudo id && sudo=\"true\" || sudo=\"false\";echo \"$sudo\"").toString().trim().split(/\r?\n/).slice(-1)) {
rep+=`${sudoerUser} is not sudoer please change this `;
} ;
}catch(err){
console.log(err);
rep+=" Check your user it seems to not be a sudoer"
}
if( conf.jwtsecret.length < 32 ) {
rep += "Your jwtsecretkey must have at least 32 characters"
}
if( conf.dns != 'unchain' && !dnsSync.resolve( `${conf.townName}.${conf.nationName}.${conf.dns}` ) ) {
rep += `\nresolving $${conf.townName}.${conf.nationName}.${conf.dns} will not responding valid IP, please setup domain redirection IP before runing this script`
}
return rep
};
Setup.config = ( townSetup ) => {
// Init this instance with a .config.js
Setup.configjs( townSetup );
// Create tribeid space + a user admin + webspace withe apxtrib webapp install
Setup.druidid( townSetup );
};
Setup.configjs = ( townSetup ) => {
// Set /config.js
let confapxtrib = fs.readFileSync( './setup/config.mustache', 'utf-8' );
fs.writeFileSync( './config.js', Mustache.render( confapxtrib, townSetup ), 'utf-8' );
if( fs.existsSync( './config.js' ) ) {
console.log( 'config.js successfully created.' );
} else {
console.log( "config.js not created, check what's wrong in tpl:", confapxtrib );
console.log( "for data :", townSetup );
process.exit();
}
};
Setup.druidid = ( townSetup ) => {
// create a tribeid with a user that will admin this instance into /tribes/tribeid /users
const config = require( '../config.js' );
// Need to do it on setup this is also done again in models/Tribes.js
console.log( `${config.tribes}/${townSetup.druidid}` )
fs.ensureDirSync( `${config.tribes}/${townSetup.druidid}` );
[ 'users', 'www', 'referentials', 'nationchains' ].forEach( r => {
fs.copySync( `${__base}/setup/tribes/apxtrib/${r}`, `${config.tribes}/${townSetup.druidid}/${r}` );
} )
/* const confcli = JSON.parse( Mustache.render( fs.readFileSync( `${__base}/setup/tribes/apxtrib/clientconf.mustache`, 'utf8' ), townSetup ) );
fs.outputJsonSync( `${config.tribes}/${townSetup.druidid}/clientconf.json`, confcli );
// Create a new tribeid + admin user for this tribeid
// with access to {druidid}:webapp as admin
*/
const Tribes = require( '../models/Tribes.js' );
const access = { app: {}, data: {} }
access.app[ `${townSetup.druidid}:webapp` ] = "admin";
access.data[ townSetup.druidid ] = { "users": "CRUDO", "referentials": "CRUDO", "www": "CRUDO" };
const createclient = Tribes.create( {
tribeid: townSetup.druidid,
genericpsw: townSetup.genericpsw,
lanquageReferential: townSetup.language,
useradmin: {
LOGIN: townSetup.login,
xlang: townSetup.language[ 0 ],
ACCESSRIGHTS: access
}
} );
if( createclient.status == 200 ) {
console.log( `Your tribeid domain was created with login : ${townSetup.login} and password: ${townSetup.genericpsw}, change it after the 1st login on https://${townSetup.subdomain}.${townSetup.domain}` );
// Create nginx conf for a first install
const confnginx = fs.readFileSync( './setup/nginx/nginx.conf.mustache', 'utf8' );
fs.outputFileSync( '/etc/nginx/nginx.conf', Mustache.render( confnginx, townSetup ), 'utf-8' );
// Create a spacedev for webapp of apxtrib
// that will be accesible in prod from https://subdomain.domain/ and in dev http://webapp.local.fr
const addspaceweb = Tribes.addspaceweb( {
setup: true,
dnsname: [ `${townSetup.subdomain}.${townSetup.domain}` ],
mode: townSetup.mode,
tribeid: townSetup.druidid,
website: 'webapp',
pageindex: "app_index_fr.html"
} );
if( addspaceweb.status == 200 ) {
console.log( `WELL DONE run yarn dev to test then yarn startpm2 ` )
}
} else {
console.log( 'Issue ', createclient )
}
}
module.exports = Setup;

View File

@ -1,311 +0,0 @@
const fs = require( 'fs-extra' );
const path = require( 'path' );
const glob = require( 'glob' );
const moment = require( 'moment' );
// Check if package is installed or not to pickup the right config file
//const config = require( '../tribes/townconf.js' );
const config={}
const Tags = {};
/*
Keyword definition:
id: b64 encoded field that can be : email , uuid
tribeid: apiamaildigit client Id, (a folder /tribes/tribeid have to exist)
email: identifiant of a person
uuid: identifiant o
contact database
operationId: code name of an operation
messageId: code name of an templatesource have to exist in /datashared/templatesource/generic/messageId
*/
/*
Manage tag data collection
Popup survey manager
*/
Tags.info = ( data, req ) => {
//console.log('headers:', req.headers)
/*console.log('hostname', req.hostname)
console.log('req.ip', req.ip)
console.log('req.ips', req.ips)
console.log('req key', Object.keys(req))
*/
//console.log('req.rawHeaders', req.body)
data.useragent = `${req.headers['user-agent']}__${req.headers['accept-language']}__${req.headers['accept-encoding']}__${req.headers['connection']}`;
data.ips = req.ips;
data.ip = req.ip;
data.proxyip = req.connection.remoteAddress;
data.cookie = ""
Object.keys( req.headers )
.forEach( k => {
if( ![ 'user-agent', 'accept-language', 'accept-encoding', 'connection' ].includes( k ) ) {
data.cookie += `${k}__${req.headers['cookie']}|`
}
} )
//data.cookie = `${req.headers['cookie']}__${req.headers['upgrade-insecure-requests']}__${req.headers['if-modified-since']}__${req.headers['if-no-match']}__${req.headers['cache-control']}`;
return data
}
Tags.getfile = ( filename, req ) => {
const infotg = filename.split( '__' );
if( infotg.length < 3 && !fs.existsSync( `${config.tribes}/${infotg[1]}` ) ) {
return {
status: 400,
payload: { info: [ 'fileUnknown' ], model: 'UploadFiles' }
}
}
if( infotg[ 0 ] == "imgtg" ) {
fs.outputJson( `${config.tribes}/${infotg[1]}/tags/imgtg/${Date.now()}.json`, Tags.info( { filename: filename, messageId: infotg[ 2 ], operationId: infotg[ 3 ], identifiant: infotg[ 4 ] }, req ), function ( err ) {
if( err ) {
console.log( `Erreur de sauvegarde de tag:${filename}` )
}
} );
return {
status: 200,
payload: { moreinfo: "Declenche tag", filename: `${__base}/public/imgtg.png` }
}
}
return { status: 404, payload: {} }
}
Tags.savehits = ( req ) => {
if( !fs.existsSync( `${config.tribes}/${req.params.tribeid}` ) ) {
console.log( `Erreur d'envoi de tag sur ${req.params.tribeid} pour ${req.params.r}` );
return false;
} else {
const info = JSON.parse( JSON.stringify( req.body ) );
fs.outputJson( `${config.tribes}/${req.params.tribeid}/tags/hits/${Date.now()}.json`, Tags.info( info, req ), function ( err ) {
if( err ) {
console.log( `Erreur de sauvegarde de tag pour ${req.params.tribeid} check si /tags/hits et /tags/imgtg exist bien ` )
}
} );
}
return true;
}
Tags.dataloadstat = ( tribeid ) => {
/*
@TODO à appeler via une route pour agregation de tag
@TODO ajouter la suppression des fichiers hits traités qd le prog aura fait ses preuves en prod
@TODO corriger la prod pour que l'ip passe
Si on recharge plusieurs fois un hits (on ne le comptabilise pas si même r et même timestamps)
Manage tag info to agregate by user and by statistique
stats/data.json = {r:{
info:{useragent:"",ip:[]},
data:[ [timestamps, tit, cookie] ]
}
}
stats/graph.json = {"graphYears": {AAAA:#visites,"years":[AAAA,AAAA]},
"graphMonths": {AAAA:{"Jan":#visites,..},"monthsLabels":["Jan",..],"years":[AAAA,]},
"graphDaysOfWeek":{"labels":["Sun","Mon",...],"Sun":#visites},
"graphHoursOfDay":{"labels":["OOh","01h",...],"00h":#visites}
}
Pour tester des evolutions ou un client en dev (recuperer son repertoire de prod /tags )
ajouter Tags.dataloadstat('yes');
NODE_ENV=dev node ./models/Tags.js
*/
const agrege = {
data: {},
graph: {
visites: {
graphYears: { years: [] },
graphMonths: {
years: [],
monthsLabels: []
},
graphMonths: {
years: [],
monthsLabels: []
},
graphDayOfWeek: { labels: [] },
graphHourOfDay: { labels: [] }
},
visitors: {
graphMonths: {
years: [],
monthsLabels: []
}
}
}
};
try {
agrege.data = fs.readJsonSync( `${config.tribes}/${tribeid}/tags/stats/data.json`, "utf-8" );
agrege.graph = fs.readJsonSync( `${config.tribes}/${tribeid}/tags/stats/graph.json`, "utf-8" );
} catch ( err ) {
console.log( "ATTENTION tag reinitialisé en data.json et graph.json, s'il s'agit de 1ere connexion pas de pb. Le risque est de perdre les tag historiques" )
//return { status: 503, payload: { info: ['Errconfig'], model: 'Tags', moreinfo: `Il manque un ${config.tribes}/${tribeid}/tags/stats/data.json ou stats/graph.json` } }
}
glob.sync( `${config.tribes}/${tribeid}/tags/hits/*` )
.forEach( f => {
const hit = fs.readJsonSync( f );
const ts = parseInt( path.basename( f )
.split( ".json" )[ 0 ] );
//console.log(moment(ts).format('DD-MM-YYYY h:mm:ss'));
const tsm = moment( ts )
const year = tsm.format( 'YYYY' );
const month = tsm.format( 'MMM' );
const dayow = tsm.format( 'ddd' );
const hourod = tsm.format( 'HH' ) + "h";
let newvisitor = false;
let alreadydone = false;
//console.log(hit.r, ts)
// Agrege data pour # visiteur vs # de visiteur
if( agrege.data[ hit.r ] ) {
if( !agrege.data[ hit.r ].data.some( el => el[ 0 ] == ts ) ) {
//evite de charger plusieurs fois le même
agrege.data[ hit.r ].data.push( [ ts, hit.tit, hit.cookie ] )
} else {
alreadydone = true;
}
} else {
newvisitor = true;
agrege.data[ hit.r ] = {
info: { useragent: hit.useragent, ip: [ hit.ip ] },
data: [
[ ts, hit.tit, hit.cookie ]
]
}
}
if( !alreadydone ) {
if( newvisitor ) {
//traite Month
if( !agrege.graph.visitors.graphMonths[ year ] ) {
agrege.graph.visitors.graphMonths[ year ] = {}
agrege.graph.visitors.graphMonths.years.push( year )
}
if( agrege.graph.visitors.graphMonths[ year ][ month ] ) {
agrege.graph.visitors.graphMonths[ year ][ month ] += 1
} else {
agrege.graph.visitors.graphMonths[ year ][ month ] = 1
agrege.graph.visitors.graphMonths.monthsLabels.push( month )
}
}
//traite graphe Year #visite
if( agrege.graph.visites.graphYears[ year ] ) {
agrege.graph.visites.graphYears[ year ] += 1
} else {
agrege.graph.visites.graphYears[ year ] = 1
agrege.graph.visites.graphYears.years.push( year )
agrege.graph.visites.graphMonths[ year ] = {}
agrege.graph.visites.graphMonths.years.push( year )
}
//traite graphe Month
if( agrege.graph.visites.graphMonths[ year ][ month ] ) {
agrege.graph.visites.graphMonths[ year ][ month ] += 1
} else {
agrege.graph.visites.graphMonths[ year ][ month ] = 1
agrege.graph.visites.graphMonths.monthsLabels.push( month )
}
//traite graphe Days of week
if( agrege.graph.visites.graphDayOfWeek[ dayow ] ) {
agrege.graph.visites.graphDayOfWeek[ dayow ] += 1
} else {
agrege.graph.visites.graphDayOfWeek[ dayow ] = 1
agrege.graph.visites.graphDayOfWeek.labels.push( dayow )
}
//traite graphe Hour of day
if( agrege.graph.visites.graphHourOfDay[ hourod ] ) {
agrege.graph.visites.graphHourOfDay[ hourod ] += 1
} else {
agrege.graph.visites.graphHourOfDay[ hourod ] = 1
agrege.graph.visites.graphHourOfDay.labels.push( hourod )
}
}
} )
fs.outputJsonSync( `${config.tribes}/${tribeid}/tags/stats/data.json`, agrege.data, 'utf-8' );
fs.outputJsonSync( `${config.tribes}/${tribeid}/tags/stats/graph.json`, agrege.graph, 'utf-8' );
return { status: 200, payload: { info: [ 'Statsupdated' ], model: 'Tags' } }
}
//console.log(Tags.dataloadstat('yes'));
/*const ar = [
[1, 1],
[1, 2]
]
console.log(ar.some(el => el[0] == 1 && el[1] == 1))
console.log(ar.some(el => el == [1, 3]))
*/
Tags.nginxlog=(pathFile)=>{
/*
Read an nginx log file and return
@TODO standardiser le log nginx pour recuperer des données (IP,...)
@return {visites:{year:month:{day:number of visites}},
visitors:{year:month:{day: number of unique visitors for the day}}
year: number of unique visitors for the year}
month:month : number of unique visitors for the month]
}
*/
const log= fs.readFileSync(pathFile,'utf-8');
const logs=log.split('\n');
console.log(`nombre ligne ${logs.length}`)
const stat={visits:{},visitors:{}};
const visitor={}
var previousdt=moment();
var previoususeragent="";
console.log(moment(previousdt).format('DD/MMM/YYYY:hh:mm:ss'))
logs.forEach(l=>{
const elt= l.split('##');
const useragent = (elt[2] && elt[2].split("\" \"")[1]) ? elt[2].split("\" \"")[1]:"unknown";
//elt[0] = [30/Jun/2022:15:15:53 +0200]
const dttime = moment(elt[0].split(' ')[0].substring(1),'DD/MMM/YYYY:hh:mm:ss');
['visits','visitors'].forEach(ch=>{
if (!stat[ch][dttime.format('YYYY')]) stat[ch][dttime.format('YYYY')]={};
if (!stat[ch][dttime.format('YYYY')][dttime.format('MMM')]) stat[ch][dttime.format('YYYY')][dttime.format('MMM')]={}
if (!stat[ch][dttime.format('YYYY')][dttime.format('MMM')][dttime.format('DD')]) stat[ch][dttime.format('YYYY')][dttime.format('MMM')][[dttime.format('DD')]]=0
if (!visitor[dttime.format('YYYY')]) visitor[dttime.format('YYYY')]={};
if (!visitor[dttime.format('YYYY')][dttime.format('MMM')]) visitor[dttime.format('YYYY')][dttime.format('MMM')]={}
if (!visitor[dttime.format('YYYY')][dttime.format('MMM')][dttime.format('DD')]) visitor[dttime.format('YYYY')][dttime.format('MMM')][[dttime.format('DD')]]=[]
})
//console.log(elt[0].split(' ')[0]+ "####" + moment(elt[0],'DD/MMM/YYYY:hh:mm:ss').format('DD-MM-YYYY h:mm:ss'));
//console.log("EEEE"+moment(previousdt).format('DD/MMM/YYYY:hh:mm:ss') + "hhhhhhh" +moment(dttime).format('DD/MMM/YYYY:hh:mm:ss'))
//console.log(previousdt!=dttime)
if (!visitor[dttime.format('YYYY')][dttime.format('MMM')][dttime.format('DD')].includes(useragent)){
visitor[dttime.format('YYYY')][dttime.format('MMM')][dttime.format('DD')].push(useragent)
}
if (previoususeragent != useragent || parseInt(Math.round(previousdt.toDate().getTime()/100000)) != parseInt(Math.round(dttime.toDate().getTime()/100000))) {
/*console.log("###########################################################");
console.log(`${previousdt.toDate().getTime()} != ${dttime.toDate().getTime()}`);
console.log(moment(previousdt).format('DD/MMM/YYYY:hh:mm:ss') + "hhhhhhh" + moment(dttime).format('DD/MMM/YYYY:hh:mm:ss'))
console.log(`useragent: ${useragent} previoususeragent: ${previoususeragent}`);
*/
stat['visits'][dttime.format('YYYY')][dttime.format('MMM')][[dttime.format('DD')]]+=1
previousdt=dttime;
previoususeragent=useragent;
}else{
//console.log("identique compte pas" )
}
})
Object.keys(visitor).forEach(y=>{
var uniqvisitoryear=[];
Object.keys(visitor[y]).forEach(m=>{
var uniqvisitormonth=[];
Object.keys(visitor[y][m]).forEach(d=>{
uniqvisitormonth = [...uniqvisitormonth, ...visitor[y][m][d]]
stat.visitors[y][m][d] = visitor[y][m][d].length
})
uniqvisitoryear=[...uniqvisitoryear, ...uniqvisitormonth]
stat.visitors[y][m][m]=uniqvisitormonth.length;
})
stat.visitors[y][y]=uniqvisitoryear.length
})
return {status:200, data:stat}
}
Tags.statin2D=(stat,pathfile)=>{
if (stat.status==200){
stat=stat.data
}else {
return stat
}
let csv="type;year;month;day;Number\n\r";
["visits", "visitors"].forEach(ch=>{
Object.keys(stat[ch]).forEach(y=>{
Object.keys(stat[ch][y]).forEach(m=>{
Object.keys(stat[ch][y][m]).forEach(d=>{
csv+=`${ch};${y};${m};${d};${stat[ch][y][m][d]}\n\r`
})
})
})
})
fs.outputFileSync(pathfile,csv);
return {status:200, info:"fileready", moreinfo:pathfile}
}
console.log(Tags.statin2D(Tags.nginxlog('/home/phil/Documents/nginx/presentation.capsthd.access.log'),'/home/phil/Documents/nginx/stat.csv'));
module.exports = Tags;

View File

@ -1,152 +0,0 @@
const fs = require( 'fs-extra' );
const path = require( 'path' );
const formidable = require( 'formidable' );
const jsonfile = require( 'jsonfile' );
const mustache = require( 'mustache' );
const config = require( '../tribes/townconf.js' );
/*
model A SUPPRIMER !!!!!!!!!!!!!!!!!!!!!!
les functions d'upload de file et de droits d'accès doivent être gérer dans Tribes
*/
const UploadFiles = {};
UploadFiles.get = function ( filename, header ) {
// check file exist
const file = `${config.tribes}/${header.xworkon}/${filename}`;
// console.log('fichier demande ', file);
if( !fs.existsSync( file ) ) {
// console.log('le fichier demande n existe pas ', file);
return {
status: 404,
payload: { info: [ 'fileUnknown' ], model: 'UploadFiles' }
};
} else {
console.log( 'envoie le fichier ', file );
return {
status: 200,
payload: { info: [ 'fileknown' ], model: 'UploadFiles', file: file }
};
}
};
UploadFiles.addjson = function ( data, header ) {
/*
Le header = {X-WorkOn:"",destinationfile:"", filename:""}
Le body = {jsonp:{},callback:function to launch after download,'code':'mot cle pour verifier que le fichier est à garder'}
*/
// console.log(req.body.jsonp);
try {
fs.outputJsonSync( header.destinationfile + '/' + header.filename, data.jsonp );
if( data.callback ) {
const execCB = require( `${__base}/models/tribeid/${
header.xworkon
}` );
execCB[ data.callback ]();
}
return {
status: 200,
payload: {
info: [ 'wellUpload' ],
model: 'UploadFiles',
render: {
destination: header.destinationfile,
filename: header.filename
}
}
};
} catch ( err ) {
console.log( 'Impossible de sauvegarder le fichier, A COMPRENDRE', err );
return {
status: 503,
payload: { info: [ 'savingError' ], model: 'UploadFiles' }
};
}
};
UploadFiles.add = function ( req, header ) {
const form = new formidable.IncomingForm();
console.log( 'req.headers', req.headers );
console.log( 'req.params', req.params );
console.log( 'req.query', req.query );
console.log( 'req.body', req.body );
let destinationfile = `${config.tribes}/${header.xworkon}/${
header.destinationfile
}`;
form.parse( req, function ( err, fields, files ) {
console.log( 'files', files.file.path );
console.log( 'fields', fields );
const oldpath = files.file.path;
destinationfile += '/' + files.file.name;
console.log( 'oldpath', oldpath );
console.log( 'destinationfile', destinationfile );
fs.copyFile( oldpath, destinationfile, function ( err ) {
if( err ) {
console.log( err );
return {
status: 500,
payload: { info: [ 'savingError' ], model: 'UploadFiles' }
};
} else {
console.log( 'passe' );
fs.unlink( oldpath );
return {
status: 200,
payload: {
info: [ 'wellUpload' ],
model: 'UploadFiles',
render: {
destination: destinationfile
}
}
};
}
} );
} );
};
UploadFiles.updateEvent = function ( domainId, eventId, event ) {
// checkAndCreateNeededDirectories(domainId);
const eventsFile = `${config.tribes}/${domainId}/actions/events/events.json`;
if( !fs.existsSync( eventsFile ) ) {
fs.outputJsonSync( eventsFile, {} );
return { status: 404, payload: 'You have not any events.' };
}
const events = fs.readJsonSync( eventsFile );
if( !events.hasOwnProperty( eventId ) ) {
return {
status: 404,
payload: 'The event you are trying to update does not exist.'
};
}
events[ eventId ] = {
eventName: event.eventName,
eventDate: event.eventDate,
eventDescription: event.eventDescription
};
fs.outputJsonSync( eventsFile, events, { spaces: 2 } );
return {
status: 200,
payload: events
};
};
UploadFiles.deleteEvent = function ( domainId, eventId ) {
// checkAndCreateNeededDirectories(domainId);
const eventsFile = `${config.tribes}/${domainId}/actions/events/events.json`;
if( !fs.existsSync( eventsFile ) ) {
fs.outputJsonSync( eventsFile, {} );
return { status: 404, payload: 'You have not any events.' };
}
const events = fs.readJsonSync( eventsFile );
if( events.hasOwnProperty( eventId ) ) {
delete events[ eventId ];
fs.outputJsonSync( eventsFile, events, { spaces: 2 } );
return {
status: 200,
payload: events
};
} else {
return {
status: 404,
payload: 'The event you are trying to delete does not exist.'
};
}
};
module.exports = UploadFiles;

View File

@ -1,4 +0,0 @@
{
"schemanotfound":"Schema not found in {{fullpath}}",
"pathnamedoesnotexist":"ObjectPath or objectName does not exist {{fullpath}}"
}

View File

@ -1,63 +0,0 @@
const express = require( 'express' );
const path = require( 'path' );
// Classes
const Messages = require( '../models/Messages.js' );
// Middlewares ( prefix, object ) => {
const checkHeaders = require( '../middlewares/checkHeaders' );
const isAuthenticated = require( '../middlewares/isAuthenticated' );
const hasAccessrighton = require( '../middlewares/hasAccessrighton' );
const router = express.Router();
router.post( '/', checkHeaders, ( req, res ) => {
/*
add message to (no authentification and accessright needs) :
a tribeid or uuid => create a contact based on email.json or phone.json or email_phone.json
if req.body.orderuuid exist then it store the req.body in /orders/orderuuid.json an order with state = order
*/
// check if a receiver is well identify if not then it send message to all user tribeid to inform **
if( !req.body.desttribeid ) req.body.desttribeid = req.session.header.xworkon;
if( !req.body.lang ) req.body.lang = req.session.header.xlang;
console.log( '/messages t send for ', req.session.header.xworkon );
//console.log(' Content: ',req.body);
const result = Messages.postinfo( req.body );
res.status( result.status )
.send( result.data )
} );
router.put( '/:objectname/:uuid', checkHeaders, isAuthenticated, ( req, res ) => {
// message that will create an object and sendback an email.
// if objectnane/uuid_lg.json exist ans accessright is ste to U for the user then it replace object data with req.body.key value
// if does not exist and accessright C then it create it with uuid
// then if req.body.tplmessage => render email with data
// No data management are done here, if need you can add plugin to create a workflow based object
// if need specific data Checkjson => req.body.callback={tribeidpugin,pluginname,function} will run pluginname.function(data) add data run specific stuf before saved the message object in /objectname/data.uuid_lg/json
let result;
console.log( "object", req.params.objectname )
if( req.params.objectname == 'notifications' ) {
//uuid is a timestamp
req.body.time = req.params.uuid;
result = Messages.notification( req.body, req.session.header );
} else {
req.body.uuid = req.params.uuid;
req.body.object = req.params.objectname;
result = Messages.object( req.body, req.session.header );
}
//console.log( 'result', result );
res.status( result.status )
.json( result.data )
} );
router.get( '/user', checkHeaders, isAuthenticated, ( req, res ) => {
// run agregate for tribeid concerned
//
console.log( "request notifiation for user", req.session.header.xpaganid );
const app = {
tribeid: req.session.header.xapp.split( ':' )[ 0 ],
website: req.session.header.xapp.split( ':' )[ 1 ],
lang: req.session.header.xlang
};
res.send( Messages.request( req.session.header.xtribe, req.session.header.xpaganid,
req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS, app ) );
} );
module.exports = router;

View File

@ -1,78 +0,0 @@
const express = require( 'express' );
const glob = require( 'glob' );
const path = require( 'path' );
// Classes
const Odmdb = require( '../models/Odmdb.js' );
// Middlewares
const checkHeaders = require( '../middlewares/checkHeaders' );
const isAuthenticated = require( '../middlewares/isAuthenticated' );
const hasAccessrighton = require( '../middlewares/hasAccessrighton' );
const router = express.Router();
router.get('/searchauth/:objectname/:question',checkHeaders,isAuthenticated,( req, res ) => {
/**
*
*
*/
console.log( 'route referentials get all language' + req.params.objectname + '-' + req.params.question );
const getref = Referentials.getref( true, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang );
// Return any status the data if any erreur return empty object
res.jsonp( getref.payload.data );
} );
router.get('schema/:objectname', checkHeaders, isAuthenticated,(req,res)=>{
/**
* @api {get} /odmdb/schema/:objectname
* @apiName GetSchema
* @apiGroup Odmdb
*
* @apiUse apxHeader
*
* @apiParam {String} objectname Mandatory if headers.xworkon == nationchains then into ./nationchains/ else into ./tribes/xworkon/
*
* @apiError (404) {string} info a key word to understand not found schema
* @apiError (404) {string} ref an string to find referential to get description of info in xlang request
* @apiError (404) {object} [moreinfo} an object with element to render ref_lg.json[info] to understand error
*
* @apiSuccess (200) {object} data contains schema requested
*
*/
const fullpath = path.resolve(`${__dirname}/tribes/${req.session.header.xworkon}/schema/${req.params.pathobjectname}.json`);
if (fs.existsSync(fullpath)){
res.status(200).json(data:fs.readJsonSync(fullpath))
}else{
res.status(404).json(info:"schemanotfound", ref:"odmdb", moreinfo:{fullpath})
}
})
router.put('schema/:objectname', checkHeaders, isAuthenticated,(req,res)=>{
/**
* @api {put} /odmdb/schema/:objectname
* @apiName putSchema
* @apiGroup Odmdb
*
* @apiUse apxHeader
*
* @apiParam {String} objectname Mandatory if headers.xworkon == nationchains then into ./nationchains/ else into ./tribes/xworkon/
* @apiBody {string} schemapath where to store schema .../schema
* @apiBody {string} objectpath where to store object ...objectname/index/config.json
* @apiBody {json} schema content
* @apiBody {json} schemalang content in lg
* @apiBody {string} lang define which schemalg is (2 letters)
*
* @apiError (404) {string} info a key word to understand not found schema
* @apiError (404) {string} ref an string to find referential to get description of info in xlang request
* @apiError (404) {object} [moreinfo} an object with element to render ref_lg.json[info] to understand error
*
* @apiSuccess (200) {object} data contains schema requested
*
*/
const fullpath = path.resolve(`${__dirname}/tribes/${req.session.header.xworkon}/schema/${req.params.pathobjectname}.json`);
const set=Odmdb.setObject(path.resolve(`${__dirname}/tribes/${req.session.header.xworkon}`),)
if (fs.existsSync(fullpath)){
res.status(200).json(data:fs.readJsonSync(fullpath))
}else{
res.status(404).json(info:"schemanotfound", ref:"odmdb", moreinfo:{fullpath})
}
})
module.exports = router;

View File

@ -1,65 +0,0 @@
// Upload de file
const express = require( 'express' );
const fs = require( 'fs-extra' );
// Classes
const UploadFile = require( '../models/UploadFiles' );
const Outputs = require( '../models/Outputs' );
//const Outputstest = require('../models/Outputstest');
// Middlewares
const checkHeaders = require( '../middlewares/checkHeaders' );
const isAuthenticated = require( '../middlewares/isAuthenticated' );
const router = express.Router();
router.post( '/ggsheet2json', checkHeaders, async ( req, res ) => {
console.log( 'route outputs sheet to json' );
let result = await Outputs.ggsheet2json( req.body, req.session.header );
res.send( result );
} );
// checkHeaders, isuploadFileValid
router.post( '/msg', checkHeaders, async ( req, res ) => {
console.log( 'route outputs msg post ' );
const envoi = await Outputs.generemsg( req.body, req.session.header );
res.status( envoi.status )
.send( {
payload: envoi.payload
} );
} );
/*test functionnalité
router.post('/msgtest', checkHeaders, isemailValid, async (req, res) => {
console.log('route outputs msg post en test');
const envoi = await Outputstest.generemsg(req.body, req.session.header);
res.status(envoi.status).send({
payload: envoi.payload
});
});
*/
router.post( '/template', checkHeaders, ( req, res ) => {
console.log( 'route outputs post de fichier template ' );
// a callback can be pass to req.body to run a specific process after upload
const saveFile = UploadFile.addjson( req.body, req.session.header );
console.log( saveFile );
res.send( saveFile );
// res.send({ status: 200, payload: { info: 'fine' } });
} );
router.post( '/pdf', checkHeaders, ( req, res ) => {
console.log( 'route outputs pdf post' );
Outputs.generepdf( req.body, req.session.header )
.then( ( doc ) => {
res.status( doc.status )
.download( doc.payload.data.path, doc.payload.data.name );
} )
.catch( ( err ) => {
console.log( err );
res.status( err.status )
.send( { payload: err.payload } );
} );
} );
module.exports = router;

View File

@ -1,94 +0,0 @@
// Upload de file
const express = require( 'express' );
const glob = require( 'glob' );
const path = require( 'path' );
// Classes
const Referentials = require( '../models/Referentials' );
// Middlewares
const checkHeaders = require( '../middlewares/checkHeaders' );
const isAuthenticated = require( '../middlewares/isAuthenticated' );
const hasAccessrighton = require( '../middlewares/hasAccessrighton' );
const router = express.Router();
/*
* keylist = list of key at 1st level in clientconf.json separated by _
* we use header.xworkon
* To manage AccesRight obkect referentials does not follow the same logic than other object this is why
*/
router.get( '/clientconf/:keylist', checkHeaders, isAuthenticated, ( req, res ) => {
// retourne liste info (non sensible) du tribeid inside headers.xworkon sur keylist ="key1_key2"
/*
if (req.session.header.accessrights.data[ "Alltribeid" ] && req.session.header.accessrights.data[ "Alltribeid" ].referentials.includes('R') ;
*/
console.log( `get clientconf for ${req.session.header.xworkon} on ${req.params.keylist}` )
let dataref = {}
if( req.params.keylist.split( '_' )
.length > 0 ) {
const ref = Referentials.clientconf( req.session.header.xworkon, req.params.keylist.split( '_' ) )
if( ref.status == 200 ) {
dataref = ref.payload.data;
} else {
console.log( "erreur ", ref )
}
}
console.log( 'envoie en jsonp: dataref' )
res.jsonp( dataref )
} );
router.get( '/clientconfglob', checkHeaders, isAuthenticated, ( req, res ) => {
res.jsonp( Referentials.clientconfglob()
.payload.data );
} );
router.get( '/contentlist/:source', checkHeaders, isAuthenticated,
( req, res ) => {
const payload = [];
console.log( req.params.source, `${config.tribes}/${req.session.header.xworkon}/referentials/dataManagement/${req.params.source}/*.json` )
glob.sync( `${config.tribes}/${req.session.header.xworkon}/referentials/dataManagement/${req.params.source}/*.json` )
.forEach( f => {
payload.push( path.basename( f, '.json' ) );
} )
res.json( payload );
} );
router.get( '/contentfull/:source/:idref', checkHeaders, isAuthenticated,
( req, res ) => {
//only for data and object
console.log( 'route referentials get all language' + req.params.source + '-' + req.params.idref );
const getref = Referentials.getref( true, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang );
// Return any status the data if any erreur return empty object
res.jsonp( getref.payload.data );
} );
router.get( '/content/:source/:idref', checkHeaders, isAuthenticated,
( req, res ) => {
console.log( 'route referentials get ' + req.params.source + '-' + req.params.idref );
const getref = Referentials.getref( false, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang );
res.jsonp( getref.payload.data );
} );
// get with no authentification
router.get( '/contentnoauth/:source/:idref', checkHeaders,
( req, res ) => {
console.log( 'route referentials get ' + req.params.source + '-' + req.params.idref );
// @TODO check access right in clientconf before sending back json file
const getref = Referentials.getref( false, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang );
res.jsonp( getref.payload.data );
} );
router.get( '/lg', ( req, res ) => {
console.log( req.headers[ "accept-language" ] )
let lg = '??';
if( req.headers[ "accept-language" ] && req.headers[ "accept-language" ].split( ',' )
.length > 0 ) {
lg = req.headers[ "accept-language" ].split( ',' )[ 0 ];
}
res.json( { lg } )
} );
router.put( '/content/:source/:idref', checkHeaders, isAuthenticated, ( req, res ) => {
console.log( `route put content for ${req.params.idref} that is a ${req.params.source}` );
const putref = Referentials.putref( req.params.source, req.params.idref, req.session.header.xworkon, req.body )
return res.status( putref.status )
.send( { payload: putref.payload } )
} );
//hasAccessrighton( 'referentials', 'U' )
router.get( '/updatefull', checkHeaders, isAuthenticated, hasAccessrighton( 'referentials', 'U' ), ( req, res ) => {
console.log( `route get to force update content updatefull is accessrighton` );
const updtref = Referentials.updatefull( req.session.header.xworkon )
return res.status( updtref.status )
.send( { payload: updtref.payload } )
} );
module.exports = router;

View File

@ -1,29 +0,0 @@
//Installation d'un tag
/*
*/
// Upload de file
const express = require('express');
// Classes
const Tags = require('../models/Tags');
// Middlewares
const router = express.Router();
router.get('/:filename', (req, res) => {
//console.log('route tags get ', req.params.filename);
const savetag = Tags.getfile(req.params.filename, req);
if(savetag.status == 200) {
res.sendFile(savetag.payload.filename);
} else {
res.status(savetag.status)
.send({ payload: savetag.payload })
}
})
router.post('/:tribeid', (req, res) => {
//console.log('route tags post ', req.params.tribeid);
const savetag = Tags.savehits(req);
res.status(200)
.send('');
})
module.exports = router;

View File

@ -1,49 +0,0 @@
// Upload de file
const express = require( 'express' );
const path = require( 'path' );
const jsonfile = require( 'jsonfile' );
const fs = require( 'fs' );
// Classes
const UploadFile = require( '../models/UploadFiles' );
// Middlewares
const checkHeaders = require( '../middlewares/checkHeaders' );
const isAuthenticated = require( '../middlewares/isAuthenticated' );
const router = express.Router();
router.post( '/', checkHeaders, ( req, res ) => {
console.log( 'route uploadFile post ' );
const saveFile = UploadFile.add( req, req.session.header );
res.send( saveFile );
// res.send({ status: 200, payload: { info: 'fine' } });
} );
router.post( '/json', checkHeaders, ( req, res ) => {
console.log( 'route uploadFile post de fichier json ' );
// a callback can be pass to req.body to run a specific process after upload
const saveFile = UploadFile.addjson( req.body, req.session.header );
console.log( saveFile );
res.send( saveFile );
// res.send({ status: 200, payload: { info: 'fine' } });
} );
router.get( '/:filename', checkHeaders, isAuthenticated, ( req, res ) => {
console.log( 'route uploadFile get ', req.params.filename );
const pushFile = UploadFile.get(
req.params.filename.replace( /______/g, '/' ),
req.session.header
);
if( pushFile.status == 200 ) {
if( path.extname( pushFile.payload.file ) === '.json' ) {
fs.readJson( pushFile.payload.file, ( err, p ) => {
if( err ) console.error( err );
res.jsonp( p );
} );
} else {
res.download( pushFile.payload.file, path.basename( pushFile.payload.file ) );
}
} else {
res.send( pushFile );
}
} );
module.exports = router;

View File

@ -1,14 +1,16 @@
const fs = require( 'fs-extra' ); const fs = require( 'fs-extra' );
const bodyParser = require( 'body-parser' ); const bodyParser = require( 'body-parser' );
const glob = require( 'glob' );
const path = require( 'path' );
const cors = require( 'cors' ); const cors = require( 'cors' );
const express = require( 'express' ); const express = require( 'express' );
const process = require('process');
/******************************************* /*******************************************
SEE https://gitea.ndda.fr/apxtrib/apxtrib/wiki/Devrules SEE https://gitea.ndda.fr/apxtrib/apxtrib/wiki/Devrules
To have a quick understanding and convention before doing deeply in source code To have a quick understanding and convention before doing deeply in source code
*********************************************/ */
// to make absolute path with `${__base}relativepath` // to make absolute path with `${__base}relativepath`
global.__base = __dirname +'/'; global.__base = __dirname +'/';
// check setup // check setup
@ -16,35 +18,50 @@ if( !fs.existsSync( '/etc/nginx/nginx.conf' ) ) {
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.' ); 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.' );
process.exit(); process.exit();
} }
if( !fs.existsSync( './nationchains/tribes/index/conf.json' ) ) { if( !fs.existsSync( './nationchains/tribes/conf.json' ) ) {
// this town is not set // this town is not set
console.log( `\x1b[42m############################################################################################\x1b[0m\n\x1b[42mWellcome into apxtrib, you must first init your town and tribes by a 'yarn setup'. \x1b[0m \n\x1b[42mThen 'yarn dev' or 'yarn startpm2' or 'yarn unittest'. Check README's project to learn more.\x1b[0m\n\x1b[42m############################################################################################\x1b[0m` ); console.log( `\x1b[42m############################################################################################\x1b[0m\n\x1b[42mWellcome into apxtrib, you must first init your town and tribes by a 'yarn setup'. \x1b[0m \n\x1b[42mThen 'yarn dev' or 'yarn startpm2' or 'yarn unittest'. Check README's project to learn more.\x1b[0m\n\x1b[42m############################################################################################\x1b[0m` );
process.exit(); process.exit();
} }
const config = require( './nationchains/tribes/index/conf.json' ); const config = require( './nationchains/tribes/conf.json' );
// Tribes allow to get local apxtrib instance context // Tribes allow to get local apxtrib instance context
// dataclient .tribeids [] .DOMs [] .routes (plugins {url:name route:path}) .appname {tribeid:[website]} // dataclient .tribeids [] .DOMs [] .routes (plugins {url:name route:path}) .appname {tribeid:[website]}
const dataclient = require( './app/models/Tribes' ) //const dataclient = require( './api/models/Tribes' ).init();
.init(); const tribelist=fs.readJsonSync(`./nationchains/tribes/idx/tribeId_all.json`);
console.log( 'allowed DOMs to access to this apxtrib server: ', dataclient.DOMs ) let doms=config.dns
const app = express(); let tribeIds=[]
let routes = glob.sync( './api/routes/*.js' )
Object.keys(config.appset).forEach(p=>{ .map( f => {
app.set(p,config.appset[p]) return { url: `/${path.basename(f,'.js')}`, route: f }
} );
//routes={url,route} check how to add plugin tribe route
Object.keys(tribelist).forEach(t=>{
tribelist[t].dns.forEach(d=>{
const dm=d.split('.').slice(-2).join('.')
if (!doms.includes(dm)) doms.push(dm)
})
tribeIds.push(t)
})
console.log('Allowed DOMs to access to this apxtrib server: ', doms )
const app = express();
Object.keys(config.api.appset).forEach(p=>{
app.set(p,config.api.appset[p])
}) })
app.set( 'trust proxy', true );
// To set depending of data form or get size to send // To set depending of data form or get size to send
app.use( bodyParser.urlencoded( config.bodyparse.urlencoded ) ); app.use( bodyParser.urlencoded( config.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( config.bodyparse.json ) ); app.use( bodyParser.json( config.api.bodyparse.json ) );
app.locals.tribeids = dataclient.tribeids; app.locals.tribeids = tribeIds;
console.log( 'app.locals.tribeids', app.locals.tribeids ); console.log( 'app.locals.tribeids', app.locals.tribeids );
// token will be store in /tmp/token/pseudo_token to check if isauthenticated
// User token authentification and user init user search // User token authentification and user init user search
const datauser = require( './models/Pagans' ) /*const datauser = require( './api/models/Pagans' )
.init( dataclient.tribeids ); .init( dataclient.tribeids );
app.locals.tokens = datauser.tokens; app.locals.tokens = datauser.tokens;
console.log( 'app.locals.tokens key ', Object.keys( app.locals.tokens ) ) console.log( 'app.locals.tokens key ', Object.keys( app.locals.tokens ) )
*/
// Cors management // Cors management
const corsOptions = { const corsOptions = {
origin: ( origin, callback ) => { origin: ( origin, callback ) => {
@ -76,15 +93,15 @@ const corsOptions = {
} }
} }
}, },
exposedHeaders: Object.keys( config.exposedHeaders ) exposedHeaders: Object.keys( config.api.exposedHeaders )
}; };
// CORS // CORS
app.use( cors( corsOptions ) ); app.use( cors( corsOptions ) );
// Static Routes // Static Routes
app.use( express.static( `${__dirname}/tribes/${config.mayorId}/www/cdn/public`, { /*app.use( express.static( `${__dirname}/nationchains/tribes/${config.mayorId}/www/cdn/public`, {
dotfiles: 'allow' dotfiles: 'allow'
} ) ); } ) );
*/
//Allow to public access a space dev delivered by apxtrib //Allow to public access a space dev delivered by apxtrib
// this is just a static open route for dev purpose, // this is just a static open route for dev purpose,
// for production, we'll use a nginx static set to /www/app/appname // for production, we'll use a nginx static set to /www/app/appname
@ -98,10 +115,10 @@ Object.keys( dataclient.appname )
*/ */
// Routers add any routes from /routes and /plugins // Routers add any routes from /routes and /plugins
console.log( 'Routes available on this apxtrib instance' ); console.log( 'Routes available on this apxtrib instance' );
console.log( dataclient.routes ); console.log( routes );
// prefix only use for dev purpose in production a proxy nginx redirect /app/ to node apxtrib // prefix only use for dev purpose in production a proxy nginx redirect /app/ to node apxtrib
dataclient.routes.forEach( r => { routes.forEach( r => {
try { try {
app.use( r.url, require( r.route ) ); app.use( r.url, require( r.route ) );
} catch ( err ) { } catch ( err ) {
@ -109,8 +126,9 @@ dataclient.routes.forEach( r => {
console.log( 'raise err-:', err ); console.log( 'raise err-:', err );
} }
} ) } )
app.listen( config.porthttp, () => {
console.log( `check in your browser that api works http://${config.dnsapxtrib}:${config.porthttp}` ); app.listen( config.api.port, () => {
console.log( `check in your browser that api works http://${config.dns}:${config.api.port}` );
} ); } );
console.log( "\x1b[42m\x1b[37m", "Made with love for people's freedom, enjoy !!!", "\x1b[0m" ); console.log( "\x1b[42m\x1b[37m", "Made with love for people's freedom, enjoy !!!", "\x1b[0m" );

View File

@ -1,111 +0,0 @@
'use strict';
const path = require( 'path' );
const fs = require( 'fs' );
const config = {};
if( !process.env.NODE_ENV ) process.env.NODE_ENV = "dev"
console.log( 'apxtrib process.env.NODE_ENV: ', process.env.NODE_ENV );
// VOIR l'ancien fichier de cnfig au cas ou il manque des chemins dans config
// voir la doc http://gitlab.ndda.fr/philc/apiamaildigitfr/wikis/InstallConf
config.prod = {
mainDir: __dirname,
tmp: path.join( __dirname, '/tmp' ),
public: path.join( __dirname, '/public' ),
archivefolder: path.join( __dirname, '/archive' ),
rootURL: '{{setupdns}}',
domain: path.join( __dirname, '/data/tribee' ),
withssl: "{{withssl}}",
SSLCredentials: {
key: path.join( __dirname, '/data/certs/{{setupdns}}.key' ),
cert: path.join( __dirname, '/data/certs/{{setupdns}}.crt' ),
ca: path.join( __dirname, '/data/certs/{{setupdns}}.csr' )
},
port: {
http: "{{httpport}}",
https: "{{httpsport}}"
},
jwtSecret: '{{jwtsecretkey}}',
saltRounds: 10,
languagesAvailable: [ 'fr', 'en', 'it', 'de', 'ru' ],
lg: {},
exposedHeaders: {
'x-auth': 'xauth',
'x-uuid': 'xuuid',
'x-language': 'xlang',
'x-client-id': 'xtribeid',
'x-workOn': 'xworkOn',
'x-app': 'xapp'
},
bodyparse: {
urlencoded: {
limit: '50mb',
extended: true
},
json: { limit: '500mb' }
}
};
// Development and test config
// apxtrib.local.fr
config.dev = {
mainDir: __dirname,
tmp: path.join( __dirname, '/tmp' ),
public: path.join( __dirname, '/public' ),
//public allow to serve on /public file into folder /public with or without login
archivefolder: path.join( __dirname, '/archive' ),
rootURL: 'apxtrib.local.fr',
domain: path.join( __dirname, '/data/tribee' ),
withssl: "YES",
SSLCredentials: {
key: path.join( __dirname, '/setup/data/certs/apxtrib.local.fr.key' ),
cert: path.join( __dirname, '/setup/data/certs/apxtrib.local.fr.crt' ),
ca: path.join( __dirname, '/setup/data/certs/apxtrib.local.fr.csr' )
},
port: {
http: "{{httpport}}",
https: "{{httpsport}}"
},
jwtSecret: 'dnsqd515+npsc^dsqdsqd^d$qdd$$$dŝqdze154615ae.Dsd:sqd!',
// Avoid authentification for uuid2 and this auth token
// Always remove this from production
devnoauthxuuid: "2",
devnoauthxauth: "autoriserparlapatrouille",
saltRounds: 10,
languagesAvailable: [ 'fr', 'en', 'it', 'de', 'ru' ],
lg: {},
exposedHeaders: {
'x-auth': 'xauth',
'x-uuid': 'xuuid',
'x-language': 'xlang',
'x-client-id': 'xtribeid',
'x-workOn': 'xworkOn',
'x-app': 'xapp'
},
bodyparse: {
urlencoded: {
limit: '50mb',
extended: true
},
json: { limit: '500mb' }
}
};
if( !config[ process.env.NODE_ENV ] ) {
console.log( 'config.js -> Exit setup due to node_ENV have to be set as prod or dev instead of ', process.env.NODE_ENV )
process.exit();
}
const confuse = config[ process.env.NODE_ENV ];
if( confuse.withssl == "YES" ) {
if( !fs.existsSync( confuse.SSLCredentials.key ) ) {
const prompt = require( 'prompt-sync' )( { sigint: true } );
//const repdata = ( process.NODE_ENV == "dev" ) ? 'devdata' : 'data';
const reinit = prompt( `Missing file to ssl ${confuse.SSLCredentials.key}, please run the process letsencrypt to get a ssl certificat or reinit project (type reinit will erase ) and answer no to question: Do you want to manage ssl : ` );
if( reinit == 'reinit' ) {
fs.removeSync( `${__dirname}/config.js` );
fs.removeSync( `${__dirname}/data` )
}
process.exit();
}
confuse.SSLCredentials.key = fs.readFileSync( confuse.SSLCredentials.key, 'utf8' );
confuse.SSLCredentials.cert = fs.readFileSync( confuse.SSLCredentials.cert, 'utf8' );
confuse.SSLCredentials.ca = fs.readFileSync( confuse.SSLCredentials.ca, 'utf8' );
}
module.exports = confuse;

View File

@ -1,37 +0,0 @@
server {
server_name {{config.apxtribDNS}};
add_header X-Request-ID $request_id; # Return to client
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Max-Age 3600;
add_header Access-Control-Expose-Headers Content-Length;
add_header Access-Control-Allow-Headers Range;
access_log /media/phil/usbfarm/apxtrib/tmp/nginx/apxtrib.crabdance.access.log main;
#location = /app {
# return 302 /app/;
#}
location /app/ {
rewrite /app/(.*$) /$1 break;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffers 32 4k;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://localhost:3017;
proxy_redirect off;
}
location / {
root /media/phil/usbfarm/apxtrib/nationchains/;
index apxtrib.html;
}
error_page 404 /media/phil/usbfarm/apxtrib/nationchains/error/404.html;
error_page 500 502 503 504 /media/phil/usbfarm/apxtrib/nationchains/error/50x.html;
}

View File

@ -1,26 +0,0 @@
const path = require( 'path' );
const config = {
loglevel:"{{consoleloglevel}}",
linuxuser:"{{linuxuser}}",
druidid:"{{druidid}}",
dnsapxtrib:"{{subdomain}}.{{domain}}",
mainDir: __dirname,
tmp: path.join( __dirname, '/tmp' ),
public: path.join( __dirname, 'data/tribe/{{druidid}}/www/cdn' ),
//(@TODO ASUP mettre /cdn de apxtrib) public allow to serve on /public file into folder /public with or without login
archivefolder: path.join( __dirname, '/archive' ),
domain: path.join( __dirname, '/data/tribe' ),
porthttp:{{porthttp}} ,
jwtSecret: '{{jwtsecret}}',
saltRounds: 10,
languagesAvailable: [ {{#language}}'{{.}}',{{/language}} ],
exposedHeaders:[ 'xauth', 'xpaganid', 'xlang', 'xtribe', 'xworkon', 'xapp' ],
bodyparse: {
urlencoded: {
limit: '50mb',
extended: true
},
json: { limit: '500mb' }
}
};
module.exports = config;

View File

@ -1,13 +0,0 @@
{
"linuxuser": "phil",
"mode": "dev",
"domain": "local.fr",
"subdomain": "dev",
"consoleloglevel": "quiet",
"porthttp": 3018,
"language": ["fr", "en"],
"jwtsecret": "longsentenceusedtoencryptionChangethisforproduction",
"druidid": "test",
"login": "testadmin",
"genericpsw": "@12ABab@"
}

View File

@ -1,9 +0,0 @@
{
"hash": "",
"previousblockhash": "",
"nextblockhash": "",
"info": "txt:freedomandthefuturofinternet##",
"time": 1643763742,
"size": "",
"difficulty": ""
}

View File

@ -1,10 +0,0 @@
{
"fixedIP":"",
"firsttimeping":0,
"lastimeping":0,
"positifping":0,
"negatifping":0,
"pubkeyadmin":"",
"tribeids":[],
"logins":[]
}

View File

@ -1,28 +0,0 @@
{
"tribeid": "{{tribeid}}",
"genericpsw": "{{genericpsw}}",
"saltRounds": "tomakeitharderbetterstronger",
"website": {
"webapp": "{{subdomain}}.{{domain}}"
},
"allowedDOMs": ["{{domain}}"],
"customization": {
"claim": "Be a Producer, not a product.",
"name": "apxtrib",
"logo": "https://{{subdomain}}.{{domain}}/cdn/{{druidid}}/img/logo/apxtrib.png",
"favicon": "https://{{subdomain}}.{{domain}}/cdn/{{druidid}}/img/iconX74x74.png",
"colors": {
"primary": "#01717B",
"secondary": "#CA5F00",
"success": "",
"info": "",
"warning": "",
"danger": "",
"light": "#fff",
"dark": "#222"
}
},
"smtp": {},
"accepted-language": "fr,en",
"langueReferential": ["fr"]
}

View File

@ -1,106 +0,0 @@
[{
"uuid": "ERRcritical",
"desc": {
"fr": "Erreur critique",
"en": "Critical Error"
}
},
{
"uuid": "failtoWritefs",
"desc": {
"fr": "Impossible d'enregistrer cette information",
"en": "Fail to write on system"
}
},
{
"uuid": "successfulCreate",
"desc": {
"fr": "Création réussie",
"en": "Creation is successful"
}
},
{
"uuid": "successfulUpdate",
"desc": {
"fr": "Mise à jour réussie",
"en": "Succesfull update"
}
},
{
"uuid": "successfulDelete",
"desc": {
"fr": "Suppression effectuée",
"en": "The user has been deleted"
}
},
{
"uuid": "forbiddenAccess",
"desc": {
"fr": "Accès non autorisé",
"en": "Forbidden access"
}
},
{
"uuid": "userNotAllowtoCreate",
"desc": {
"fr": "L'utilisateur n'est pas authorisé à créer un nouvel utilisateur",
"en": "Pagans is not allowed to create a new user account"
}
},
{
"uuid": "userNotAllowtoUpdate",
"desc": {
"fr": "L'utilisateur n'est pas authorisé à mettre à jour cet utilisateur",
"en": "Pagans is not allowed to update this user account"
}
},
{
"uuid": "userNotAllowtoDelete",
"desc": {
"fr": "L'utilisateur n'est pas authrisé à supprimer utilisateur",
"en": "Pagans is not allowed to delete a user account"
}
},
{
"uuid": "invalidData",
"desc": {
"fr": "Vérifiez vos données",
"en": "Check your data"
}
},
{
"uuid": "ERRemail",
"desc": {
"fr": "Vérifiez votre email",
"en": "Check your email"
}
},
{
"uuid": "Reservationplandoesnotexist",
"desc": {
"fr": "Il n'y a pas de Planning de réservation",
"en": "No reservation plan at this adress"
}
},
{
"uuid": "Reservationitemwelldone",
"desc": {
"fr": "Votre reservation a bien été enregistrée",
"en": "Registration well done."
}
},
{
"uuid": "Nomoreavailability",
"desc": {
"fr": "Désolé, la place n'est plus disponible",
"en": "Unavailable."
}
},
{
"uuid": "CatalogdoesnotExist",
"desc": {
"fr": "Désolé, ce catagoue n'existe pas",
"en": "This catalog does not exist."
}
}
]

View File

@ -1,170 +0,0 @@
[
{
"uuid": "ERRcritical",
"desc": {
"fr": "Erreur critique",
"en": "Critical Error"
}
},
{
"uuid": "msgsentok",
"desc": {
"fr": "L'email a bien été envoyé",
"en": "email sent"
}
},
{
"uuid": "emailAlreadyExist",
"desc": {
"fr": "Cet email a déjà un compte",
"en": "Email already exists"
}
},
{
"uuid": "failtoWritefs",
"desc": {
"fr": "Impossible d'enregistrer cette information",
"en": "Fail to write on system"
}
},
{
"uuid": "successfulCreate",
"desc": {
"fr": "Création réussie",
"en": "Creation is successful"
}
},
{
"uuid": "successfulUpdate",
"desc": {
"fr": "Mise à jour réussie",
"en": "Succesfull update"
}
},
{
"uuid": "successfulDelete",
"desc": {
"fr": "Suppression effectuée",
"en": "The user has been deleted"
}
},
{
"uuid": "serverNeedAuthentification",
"desc": {
"fr": "Ce serveur nécessite une authentification",
"en": "This server needs authentification"
}
},
{
"uuid": "forbiddenAccess",
"desc": {
"fr": "Accès non autorisé",
"en": "Forbidden access"
}
},
{
"uuid": "userNotAllowtoCreate",
"desc": {
"fr": "L'utilisateur n'est pas authorisé à créer un nouvel utilisateur",
"en": "Pagans is not allowed to create a new user account"
}
},
{
"uuid": "userNotAllowtoUpdate",
"desc": {
"fr": "L'utilisateur n'est pas authorisé à mettre à jour cet utilisateur",
"en": "Pagans is not allowed to update this user account"
}
},
{
"uuid": "userNotAllowtoDelete",
"desc": {
"fr": "L'utilisateur n'est pas authrisé à supprimer utilisateur",
"en": "Pagans is not allowed to delete a user account"
}
},
{
"uuid": "useridNotfound",
"desc": {
"fr": "L'utilisateur {{uuid}} n'existe pas sur {{tribeid}}",
"en": "Pagans {{uuid}} not found for {{tribeid}}"
}
},
{
"uuid": "useremailNotfound",
"desc": {
"fr": "L'email n'existe pas",
"en": "Email not found"
}
},
{
"uuid": "loginDoesNotExist",
"desc": {
"fr": "Ce login n'existe pas",
"en": "This login doesn't exist"
}
},
{
"uuid": "checkCredentials",
"desc": {
"fr": "Vérifiez vos identifiants",
"en": "Check your credentials"
}
},
{
"uuid": "wrongPassword",
"desc": {
"fr": "Vérifiez votre mot de passe",
"en": "Check your password"
}
},
{
"uuid": "invalidData",
"desc": {
"fr": "Vérifiez vos données",
"en": "Check your data"
}
},
{
"uuid": "pswTooSimple",
"desc": {
"fr": "Le mot de passe doit faire au moins 8 caractéres comporter au moins un chiffre, une lettre minuscule, une lettre majuscule et un caractere spécial type @ !...",
"en": "Password too simple, need to contain at least 8 caracters lower and uppercase, number and @! ..."
}
},
{
"uuid": "ERRemail",
"desc": {
"fr": "Vérifiez votre email",
"en": "Check your email"
}
},
{
"uuid": "ERRnewnewbisdiff",
"desc": {
"fr": "Le mot de passe de confirmation ne correspond pas",
"en": "Check your confirmation password"
}
},
{
"uuid": "ERRnotemplate",
"desc": {
"fr": "il n'y a pas de template d'email dans la demande template.html est vide et pas de htmlfile présent.",
"en": "Check your email template conf tribeid no msg.template.htmlfile and msg.html==''"
}
},
{
"uuid": "wellPdfGenerated",
"desc": {
"fr": "Le pdf: {{filename}} a ete genere correctement.",
"en": "Pdf well generated"
}
},
{
"uuid": "pdfGenerationError",
"desc": {
"fr": "Erreur dans la generation de pdf, verifiez le json",
"en": "Error in pdf generation, check the json"
}
}
]

View File

@ -1,23 +0,0 @@
[
{
"uuid": "fileUnknown",
"desc": {
"fr": "Fichier inconnu",
"en": "File unknown"
}
},
{
"uuid": "wellUpload",
"desc": {
"fr": "Fichier bien récupéré dans {{destination}}/{{filename}}",
"en": "File well uploaded in {{destination}}/{{filename}}"
}
},
{
"uuid": "savingError",
"desc": {
"fr": "Impossible de sauvegarder",
"en": "Saving file is impossible"
}
}
]

View File

@ -1,149 +0,0 @@
[
{
"uuid": "ERRcritical",
"desc": {
"fr": "Erreur critique",
"en": "Critical Error"
}
},
{
"uuid": "loginAlreadyExist",
"desc": {
"fr": "Ce login est déjà attribué",
"en": "Login already exists"
}
},
{
"uuid": "emailAlreadyExist",
"desc": {
"fr": "Cet email a déjà un compte",
"en": "Email already exists"
}
},
{
"uuid": "failtoWritefs",
"desc": {
"fr": "Impossible d'enregistrer cette information",
"en": "Fail to write on system"
}
},
{
"uuid": "successfulCreate",
"desc": {
"fr": "Création réussie",
"en": "Creation is successful"
}
},
{
"uuid": "successfulUpdate",
"desc": {
"fr": "Mise à jour réussie",
"en": "Succesfull update"
}
},
{
"uuid": "successfulDelete",
"desc": {
"fr": "Suppression effectuée",
"en": "The user has been deleted"
}
},
{
"uuid": "serverNeedAuthentification",
"desc": {
"fr": "Ce serveur nécessite une authentification",
"en": "This server needs authentification"
}
},
{
"uuid": "forbiddenAccess",
"desc": {
"fr": "Accès non autorisé",
"en": "Forbidden access"
}
},
{
"uuid": "userNotAllowtoCreate",
"desc": {
"fr": "L'utilisateur n'est pas authorisé à créer un nouvel utilisateur",
"en": "Pagans is not allowed to create a new user account"
}
},
{
"uuid": "userNotAllowtoUpdate",
"desc": {
"fr": "L'utilisateur n'est pas authorisé à mettre à jour cet utilisateur",
"en": "Pagans is not allowed to update this user account"
}
},
{
"uuid": "userNotAllowtoDelete",
"desc": {
"fr": "L'utilisateur n'est pas authrisé à supprimer utilisateur",
"en": "Pagans is not allowed to delete a user account"
}
},
{
"uuid": "useridNotfound",
"desc": {
"fr": "L'utilisateur {{uuid}} n'existe pas sur {{tribeid}}",
"en": "Pagans {{uuid}} not found for {{tribeid}}"
}
},
{
"uuid": "useremailNotfound",
"desc": {
"fr": "L'email n'existe pas",
"en": "Email not found"
}
},
{
"uuid": "loginDoesNotExist",
"desc": {
"fr": "Ce login n'existe pas",
"en": "This login doesn't exist"
}
},
{
"uuid": "checkCredentials",
"desc": {
"fr": "Vérifiez vos identifiants",
"en": "Check your credentials"
}
},
{
"uuid": "wrongPassword",
"desc": {
"fr": "Vérifiez votre mot de passe",
"en": "Check your password"
}
},
{
"uuid": "invalidData",
"desc": {
"fr": "Vérifiez vos données",
"en": "Check your data"
}
},
{
"uuid": "pswTooSimple",
"desc": {
"fr": "Le mot de passe doit faire au moins 8 caractéres comporter au moins un chiffre, une lettre minuscule, une lettre majuscule et un caractere spécial type @ !...",
"en": "Password too simple, need to contain at least 8 caracters lower and uppercase, number and @! ..."
}
},
{
"uuid": "ERRemail",
"desc": {
"fr": "Vérifiez votre email",
"en": "Check your email"
}
},
{
"uuid": "ERRnewnewbisdiff",
"desc": {
"fr": "Le mot de passe de confirmation ne correspond pas",
"en": "Check your confirmation password"
}
}
]

View File

@ -1,12 +0,0 @@
[
{
"uuid": 0,
"desclong": { "fr": "Monsieur", "en": "Mister" },
"desc": { "fr": "M.", "en": "M." }
},
{
"uuid": 1,
"desclong": { "fr": "Madame", "en": "Miss" },
"desc": { "fr": "Mme", "en": "Miss" }
}
]

View File

@ -1,314 +0,0 @@
[
{
"uuid": "AMDTA",
"desc": { "fr": "Amiante (DTA)" },
"desclong": {
"fr": "correspond au champ diag_01 dans le modèle de rapport Ordre de mission"
},
"color": "#449245"
},
{
"uuid": "AMVENT",
"desc": { "fr": "Amiante (Vente)" },
"desclong": {
"fr": "correspond au champ diag_02 dans le modèle de rapport Ordre de mission"
},
"color": "#136202"
},
{
"uuid": "AMTRAV",
"desc": { "fr": "Amiante (Travaux)" },
"desclong": {
"fr": "correspond au champ diag_03 dans le modèle de rapport Ordre de mission"
},
"color": "#865694"
},
{
"uuid": "AMDEMOL",
"desc": { "fr": "Amiante (Démol)" },
"desclong": {
"fr": "correspond au champ diag_04 dans le modèle de rapport Ordre de mission"
},
"color": "#086446"
},
{
"uuid": "DIAGTERM",
"desc": { "fr": "Diag.Termites" },
"desclong": {
"fr": "correspond au champ diag_05 dans le modèle de rapport Ordre de mission"
},
"color": "#036034"
},
{
"uuid": "DIAGPARA",
"desc": { "fr": "Diag.Parasites" },
"desclong": {
"fr": "correspond au champ diag_06 dans le modèle de rapport Ordre de mission"
},
"color": "#116801"
},
{
"uuid": "CARREZ",
"desc": { "fr": "Mesurage (Carrez)" },
"desclong": {
"fr": "correspond au champ diag_07 dans le modèle de rapport Ordre de mission"
},
"color": "#341770"
},
{
"uuid": "CREP",
"desc": { "fr": "Constat des risques d'exposition au plomb (CREP)" },
"desclong": {
"fr": "correspond au champ diag_08 dans le modèle de rapport Ordre de mission"
},
"color": "#303924"
},
{
"uuid": "ASSAINISS",
"desc": { "fr": "Assainissement" },
"desclong": {
"fr": "correspond au champ diag_09 dans le modèle de rapport Ordre de mission"
},
"color": "#279573"
},
{
"uuid": "PISCINE",
"desc": { "fr": "Piscine" },
"desclong": {
"fr": "correspond au champ diag_10 dans le modèle de rapport Ordre de mission"
},
"color": "#450176"
},
{
"uuid": "GAZ",
"desc": { "fr": "Gaz" },
"desclong": {
"fr": "correspond au champ diag_11 dans le modèle de rapport Ordre de mission"
},
"color": "#763822"
},
{
"uuid": "ELEC",
"desc": { "fr": "Electricité" },
"desclong": {
"fr": "correspond au champ diag_12 dans le modèle de rapport Ordre de mission"
},
"color": "#873048"
},
{
"uuid": "SRU",
"desc": { "fr": "D.Technique SRU" },
"desclong": {
"fr": "correspond au champ diag_13 dans le modèle de rapport Ordre de mission"
},
"color": "#279870"
},
{
"uuid": "DPE",
"desc": { "fr": "DPE" },
"desclong": {
"fr": "correspond au champ diag_14 dans le modèle de rapport Ordre de mission"
},
"color": "#862302"
},
{
"uuid": "TX0",
"desc": { "fr": "Prêt à taux zéro" },
"desclong": {
"fr": "correspond au champ diag_15 dans le modèle de rapport Ordre de mission"
},
"color": "#279050"
},
{
"uuid": "ERNT",
"desc": { "fr": "ERNT" },
"desclong": {
"fr": "correspond au champ diag_16 dans le modèle de rapport Ordre de mission"
},
"color": "#870447"
},
{
"uuid": "ROBIEN",
"desc": { "fr": "Robien" },
"desclong": {
"fr": "correspond au champ diag_17 dans le modèle de rapport Ordre de mission"
},
"color": "#238577"
},
{
"uuid": "ETATLIEU",
"desc": { "fr": "Etat des lieux" },
"desclong": {
"fr": "correspond au champ diag_18 dans le modèle de rapport Ordre de mission"
},
"color": "#159488"
},
{
"uuid": "DIAGPBEAU",
"desc": { "fr": "Diag. plomb dans l'eau" },
"desclong": {
"fr": "correspond au champ diag_19 dans le modèle de rapport Ordre de mission"
},
"color": "#210836"
},
{
"uuid": "ASCENSE",
"desc": { "fr": "Ascenseur" },
"desclong": {
"fr": "correspond au champ diag_20 dans le modèle de rapport Ordre de mission"
},
"color": "#702852"
},
{
"uuid": "RADON",
"desc": { "fr": "Radon" },
"desclong": {
"fr": "correspond au champ diag_21 dans le modèle de rapport Ordre de mission"
},
"color": "#851497"
},
{
"uuid": "INCENDIE",
"desc": { "fr": "Incendie" },
"desclong": {
"fr": "correspond au champ diag_22 dans le modèle de rapport Ordre de mission"
},
"color": "#329688"
},
{
"uuid": "HANDICAP",
"desc": { "fr": "Handicapé" },
"desclong": {
"fr": "correspond au champ diag_23 dans le modèle de rapport Ordre de mission"
},
"color": "#752339"
},
{
"uuid": "BOUTIN",
"desc": { "fr": "Mesurage (Boutin)" },
"desclong": {
"fr": "correspond au champ diag_24 dans le modèle de rapport Ordre de mission"
},
"color": "#645556"
},
{
"uuid": "AMDAPP",
"desc": { "fr": "Amiante DAPP" },
"desclong": {
"fr": "correspond au champ diag_25 dans le modèle de rapport Ordre de mission"
},
"color": "#594067"
},
{
"uuid": "DRIPP",
"desc": { "fr": "DRIPP" },
"desclong": {
"fr": "correspond au champ diag_26 dans le modèle de rapport Ordre de mission"
},
"color": "#135691"
},
{
"uuid": "DPN",
"desc": { "fr": "DPN Performance numérique" },
"desclong": {
"fr": "correspond au champ diag_27 dans le modèle de rapport Ordre de mission"
},
"color": "#659536"
},
{
"uuid": "INFILTRO",
"desc": { "fr": "Infiltrométrie" },
"desclong": {
"fr": "correspond au champ diag_28 dans le modèle de rapport Ordre de mission"
},
"color": "#931708"
},
{
"uuid": "AMAPTVX",
"desc": { "fr": "Amiante Examun Visuel APTVX" },
"desclong": {
"fr": "correspond au champ diag_29 dans le modèle de rapport Ordre de mission"
},
"color": "#165812"
},
{
"uuid": "DECHET",
"desc": { "fr": "Dechet" },
"desclong": {
"fr": "correspond au champ diag_30 dans le modèle de rapport Ordre de mission"
},
"color": "#682853"
},
{
"uuid": "PBAPTVX",
"desc": { "fr": "Plomb APTVX" },
"desclong": {
"fr": "correspond au champ diag_31 dans le modèle de rapport Ordre de mission"
},
"color": "#051199"
},
{
"uuid": "AMCTRLPERIO",
"desc": { "fr": "Amiante Contrôl périodique" },
"desclong": {
"fr": "correspond au champ diag_32 dans le modèle de rapport Ordre de mission"
},
"color": "#726364"
},
{
"uuid": "AMEMPOUSS",
"desc": { "fr": "Amiante Empoussièrement" },
"desclong": {
"fr": "correspond au champ diag_33 dans le modèle de rapport Ordre de mission"
},
"color": "#053460"
},
{
"uuid": "DEVINTERNE",
"desc": { "fr": "Module developpement Interne" },
"desclong": {
"fr": "correspond au champ diag_34 dans le modèle de rapport Ordre de mission"
},
"color": "#687134"
},
{
"uuid": "HOMEINSPECT",
"desc": { "fr": "Home Inspection" },
"desclong": {
"fr": "correspond au champ diag_35 dans le modèle de rapport Ordre de mission"
},
"color": "#574776"
},
{
"uuid": "4PTINSPECTION",
"desc": { "fr": "4PT Inspection" },
"desclong": {
"fr": "correspond au champ diag_36 dans le modèle de rapport Ordre de mission"
},
"color": "#729909"
},
{
"uuid": "WINDMITIG",
"desc": { "fr": "Wind Mitigation Inspection" },
"desclong": {
"fr": "correspond au champ diag_37 dans le modèle de rapport Ordre de mission"
},
"color": "#646189"
},
{
"uuid": "PBAVTVX",
"desc": { "fr": "Plomb Av Tvx" },
"desclong": {
"fr": "correspond au champ diag_37 DIAG_38 dans le modèle de rapport Ordre de mission"
},
"color": "#971402"
},
{
"uuid": "HAP",
"desc": { "fr": "HAP" },
"desclong": {
"fr": "correspond au champ DIAG_39 dans le modèle de rapport Ordre de mission"
},
"color": "#577844"
}
]

View File

@ -1,46 +0,0 @@
[
{
"uuid": "USER",
"desc": {
"fr": "USER - Utilisateur interne",
"en": "USER - User profil"
},
"desclong": {
"fr": "Utilisateur interne à l'organisation",
"en": "User profil"
}
},
{
"uuid": "CLIENT",
"desc": {
"fr": "CLIENT - Utilisateur externe",
"en": "CLIENT - User profil"
},
"desclong": {
"fr": "Utilisateur externe type client",
"en": "User profil"
}
},
{
"uuid": "MANAGER",
"desc": {
"fr": "MANAGER - Gestionnaire de données",
"en": "MANAGER - Data Manager"
},
"desclong": {
"fr": "Gestionnaire de données avec des accès sensible",
"en": "Data Manager with sensible data access"
}
},
{
"uuid": "ADMIN",
"desc": {
"fr": "ADMIN - Admininstrateur",
"en": "ADMIN - Admin profil"
},
"desclong": {
"fr": "Admininstrateur avec accès complet aux comptes",
"en": "Admin profil with full access"
}
}
]

View File

@ -1,17 +0,0 @@
[
{
"uuid": "OTHER",
"desclong": { "fr": "Autre", "en": "Other" },
"desc": { "fr": "Aut.", "en": "Oth." }
},
{
"uuid": "DIAG",
"desclong": { "fr": "Diagnostiqueur", "en": "Diag" },
"desc": { "fr": "Diag", "en": "DIAG" }
},
{
"uuid": "GEST",
"desclong": { "fr": "Gestion", "en": "Management" },
"desc": { "fr": "Gest", "en": "Manag" }
}
]

View File

@ -1,129 +0,0 @@
{
"commentaire": "Parametrage permettant de mettre à jour le cataloguecatBoutiquefixe.json",
"nomcatalogue": "",
"objet": "companies",
"optioncatalogcsv": {
"retln": "\n",
"sep": ";",
"seplevel": "__",
"replacespecialcarCsv2Json": "[[/Semicolon/g,';']]",
"replacespecialcarJson2Csv": "[[/;/g, 'Semicolon']]"
},
"removeforPublic": "",
"templates": {
"templateidintro": "",
"menu": "",
"header": "",
"section": "",
"filtre": "bdcfiltercateg",
"card": "bdccard"
},
"vendeur": {
"nom": "Commune dIgny",
"siret": "333 951 978 00050",
"responsable": "Marie Faujas (Directrice de la Communication, Culture et Evènementiel)",
"adressesociale": "23, avenue de la division Leclerc",
"CP": "91430",
"ville": "IGNY",
"logo": "logo.png",
"email": "mairie@igny.fr",
"tel": "01 69 33 11 19",
"telinter": "33169331119",
"cartegmap": "",
"reseauxociaux": [],
"horaire": "",
"horairedata": "",
"IBAN": "",
"tribunalRCS": "",
"ScanKbis": "",
"RIBSociete": "",
"ScanIdcardResp1": "",
"JustifDomicileResp1": "",
"ScanIdcardResp2": "",
"JustifDomicileResp2": ""
},
"hebergeur": {
"nom": "SAS Need-Data",
"adresse": "6 Avenue des Andes",
"CP": "91940",
"Ville": "Les Ulis",
"site": "https://need-data.com"
},
"page": {
"objettype": "page",
"nom": "",
"urlsite": "https://shop.igny.fr",
"couleurprimaire": "",
"couleursecondaire": "",
"description": "",
"metaauthor": "",
"keywords": "",
"ogtitle": "",
"ogvignette": "",
"title": "",
"ordre": []
},
"header": {
"objettype": "html",
"photopleinepage": "",
"TITREpage": "",
"SSTITREpage": "",
"inscriptionemailbouton": "S'inscrire",
"TEXTpage": ""
},
"edito": {
"objettype": "html",
"tmpl": "sectionmaildigit",
"contenthtml": "static/data/staticContentwebsite/edito.html"
},
"referencer": {
"objettype": "html",
"tmpl": "sectionmaildigit",
"contenthtml": "static/data/staticContentwebsite/referencer.html"
},
"footer": {
"objettype": "html",
"tmpl": "sectionmaildigit",
"classsection": "footer text-center bg-primary text-white",
"contenthtml": "static/data/staticContentwebsite/footer.html"
},
"catalogue": {
"objettype": "catalogueCards",
"tmpl": "sectionmaildigit",
"tpl": "",
"titre": "",
"sstitre": "",
"text": "",
"youtube": "",
"youtubesmallscreen": "",
"youtubebtn": "",
"filtrecatalog": {
"tpl": "bdcfiltercateg",
"btnlist": true,
"seleclist": false,
"classbtn": "btn-outline-primary",
"modalbutton": "video pour passer commande",
"modalcontent": "",
"modalcontentsmallscreen": "",
"classcolfiltre": "text-left",
"titrefiltre": "",
"message": " <p><b>La livraison est offerte à partir de <s>6 cartons</s> 2 cartons (pendant la période de confinement)</b></p>",
"categorie": "Nos Gammes",
"btncategorie": "btn-outline-primary",
"item": []
},
"cards": {
"tpl": "bdccard",
"devise": "€",
"buttonajoutpanier": true,
"showAvailibility": false,
"masqueitemifnomoreavailable": true,
"buttonBookwithemail": false,
"buttonBookaddForm": true,
"cardClass": "col-12",
"btndesc": "Ajouter cette réservation",
"cardbtn": "btn-primary",
"objet": {}
}
}
}

View File

@ -1,18 +0,0 @@
{
"commentaire": "Spécification permettant d'importer et d'exporter en csv des companies, pour documentation voir gitlab",
"object": "companies",
"cardscsv": "compagniesIGNY.csv",
"ASUPPcatalogPerso": "catalogueCommerceIGNY.csv",
"optioncardscsv": {
"retln": "\n",
"sep": ";",
"champs": ["UUID", "TYPE", "STATUT", "CATEGORIE", "TITRE", "SSTITRE", "KEYWORD", "MOTHTMLDUMAGASIN", "MOTTXTDUMAGASIN", "ADRESSE_PRO", "CP_PRO", "VILLE_PRO", "PHONE_PRO", "HORAIRESDESC", "HORAIREDATA", "URL", "FACEBOOK", "INSTA", "YOUTUBE", "LINKEDIN", "EMAIL_PRO", "IMG_VIGNETTE", "DATEOUVERTURE", "DATEFERMETURE", "HTML", "COMMENTPOSTTRT", "DATE_CREATE", "DATE_UPDATE"],
"array": ["CATEGORIE", "PHONE_PRO", "EMAIL_PRO"],
"arraysplitsep": ",",
"numericfield": [],
"search": "(fiche.UUID && fiche.UUID == data.UUID) || (fiche.EMAIL_PRO && utils.testinarray(fiche.EMAIL_PRO,data.EMAIL_PRO)) || (fiche.PHONE_PRO && utils.testinarray(fiche.PHONE_PRO,data.PHONE_PRO))",
"merge": [],
"replacespecialcarCsv2Json": "[[/Semicolon/g,';']]",
"replacespecialcarJson2Csv": "[[/;/g, 'Semicolon']]"
}
}

View File

@ -1,134 +0,0 @@
{
"fr": {
"menuleft": {
"sbbrandlink": "app.html",
"sbtitle": "YES",
"sbgroupmenu": [{
"groupheader": "Suivi",
"sbssgroupmenu": [{
"name": "Reporting",
"icon": "sliders",
"actionclick": "pwa.reporting.init()"
}, {
"name": "Test sous niveau",
"icon": "sliders",
"actionclick": "pwa.reporting.init()",
"iditemmenus": "suivitest",
"itemmenus": [{
"name": "sousmenu",
"actionclick": "pwa.reporting.init()"
}]
}]
}, {
"groupheader": "Admin",
"sbssgroupmenu": [{
"name": "Pagans",
"icon": "sliders",
"actionclick": "pwa.users.init()"
}, {
"name": "Referentiels",
"icon": "sliders",
"iditemmenus": "adminreferentiel",
"itemmenus": [{
"name": "Offre",
"actionclick": "pwa.referential.setting('offre')"
}, {
"name": "return action",
"actionclick": "pwa.referential.setting('returnaction')"
}, {
"name": "data",
"actionclick": "pwa.referential.setting('data')"
}, {
"name": "json",
"actionclick": "pwa.referential.setting('json')"
}, {
"name": "Objects",
"actionclick": "pwa.referential.setting('object')"
}]
}]
}, {
"groupheader": "Teacher",
"sbssgroupmenu": [{
"name": "Evaluation",
"icon": "sliders",
"actionclick": "pwa.evaluation.init()"
}, {
"name": "ScheduleOnce",
"icon": "sliders",
"actionclick": "pwa.scheduleonce.init()"
}]
}, {
"groupheader": "Operation",
"sbssgroupmenu": [{
"name": "Action Learner",
"icon": "sliders",
"actionclick": "pwa.actionlearner.init()"
}, {
"name": "Action teacher",
"icon": "sliders",
"actionclick": "pwa.actionteacher.init()"
}]
}, {
"groupheader": "Marketing",
"sbssgroupmenu": [{
"name": "Gestion l'offre",
"icon": "sliders",
"actionclick": "pwa.offers.init()"
}, {
"name": "Action teacher",
"icon": "sliders",
"actionclick": "pwa.actionteacher.init()"
}]
}, {
"groupheader": "Learner",
"sbssgroupmenu": [{
"name": "Mes evaluations",
"icon": "sliders",
"actionclick": "pwa.learner.init()"
},
{
"name": "Actions learner",
"icon": "sliders",
"actionclick": "pwa.learner.action()"
}
]
}]
},
"menutop": {
"withsearch": true,
"searchtxt": "Recherche...",
"withnotification": true,
"notificationheader": "Vos notifications",
"notificationfooter": "Voir toutes les notifications",
"href": "?action=notification.view",
"withmessage": false,
"messageheader": "Vos messages non lus",
"messagefooter": "Voir tous les messages",
"avatarimg": "",
"name": "",
"menuprofil": [{
"icon": "user",
"desc": "Profile",
"href": "?action=user.settings",
"menubreaker": false
},
{
"icon": "pie-chart",
"desc": "Activity",
"href": "?action=user.activity",
"menubreaker": true
},
{
"icon": "settings",
"desc": "Log out",
"href": "?action=userauth.logout",
"menubreaker": false
}
]
}
},
"en": {
"menuleft": {},
"menutop": {}
}
}

View File

@ -1,134 +0,0 @@
{
"fr": {
"menuleft": {
"sbbrandlink": "app.html",
"sbtitle": "YES",
"sbgroupmenu": [{
"groupheader": "Suivi",
"sbssgroupmenu": [{
"name": "Reporting",
"icon": "sliders",
"actionclick": "pwa.reporting.init()"
}, {
"name": "Test sous niveau",
"icon": "sliders",
"actionclick": "pwa.reporting.init()",
"iditemmenus": "suivitest",
"itemmenus": [{
"name": "sousmenu",
"actionclick": "pwa.reporting.init()"
}]
}]
}, {
"groupheader": "Admin",
"sbssgroupmenu": [{
"name": "Pagans",
"icon": "sliders",
"actionclick": "pwa.users.init()"
}, {
"name": "Referentiels",
"icon": "sliders",
"iditemmenus": "adminreferentiel",
"itemmenus": [{
"name": "Offre",
"actionclick": "pwa.referential.setting('offre')"
}, {
"name": "return action",
"actionclick": "pwa.referential.setting('returnaction')"
}, {
"name": "data",
"actionclick": "pwa.referential.setting('data')"
}, {
"name": "json",
"actionclick": "pwa.referential.setting('json')"
}, {
"name": "Objects",
"actionclick": "pwa.referential.setting('object')"
}]
}]
}, {
"groupheader": "Teacher",
"sbssgroupmenu": [{
"name": "Evaluation",
"icon": "sliders",
"actionclick": "pwa.evaluation.init()"
}, {
"name": "ScheduleOnce",
"icon": "sliders",
"actionclick": "pwa.scheduleonce.init()"
}]
}, {
"groupheader": "Operation",
"sbssgroupmenu": [{
"name": "Action Learner",
"icon": "sliders",
"actionclick": "pwa.actionlearner.init()"
}, {
"name": "Action teacher",
"icon": "sliders",
"actionclick": "pwa.actionteacher.init()"
}]
}, {
"groupheader": "Marketing",
"sbssgroupmenu": [{
"name": "Gestion l'offre",
"icon": "sliders",
"actionclick": "pwa.offers.init()"
}, {
"name": "Action teacher",
"icon": "sliders",
"actionclick": "pwa.actionteacher.init()"
}]
}, {
"groupheader": "Learner",
"sbssgroupmenu": [{
"name": "Mes evaluations",
"icon": "sliders",
"actionclick": "pwa.learner.init()"
},
{
"name": "Actions learner",
"icon": "sliders",
"actionclick": "pwa.learner.action()"
}
]
}]
},
"menutop": {
"withsearch": true,
"searchtxt": "Recherche...",
"withnotification": true,
"notificationheader": "Vos notifications",
"notificationfooter": "Voir toutes les notifications",
"href": "?action=notification.view",
"withmessage": false,
"messageheader": "Vos messages non lus",
"messagefooter": "Voir tous les messages",
"avatarimg": "",
"name": "",
"menuprofil": [{
"icon": "user",
"desc": "Profile",
"href": "?action=user.settings",
"menubreaker": false
},
{
"icon": "pie-chart",
"desc": "Activity",
"href": "?action=user.activity",
"menubreaker": true
},
{
"icon": "settings",
"desc": "Log out",
"href": "?action=userauth.logout",
"menubreaker": false
}
]
}
},
"en": {
"menuleft": {},
"menutop": {}
}
}

View File

@ -1,70 +0,0 @@
{
"fr": {
"titre": "Gestion des référentiels Administrateur",
"submenutitre": "Liste",
"btnsave": "Sauvegarder",
"btndelete": "Supprimer",
"btncopy": "Dupliquer",
"copyplaceholder": "avec le nom de referentiel",
"submenuitems": [{
"active": "active",
"groupinfo": "menuAdmin",
"id": "referentialmenuadmin",
"optionjsoneditor": {
"theme": "tailwind"
},
"onclick": "pwa.referential.save(event,'referentialmenuadmin')"
}, {
"active": "",
"id": "referentialmenuteacher",
"optionjsoneditor": {},
"groupinfo": "menuTeacher",
"onclick": "pwa.referential.save(event,'referentialmenuteacher')"
},
{
"active": "",
"id": "referentialusersetting",
"groupinfo": "usersetting",
"optionjsoneditor": {},
"btnsave": "Sauvegarder",
"onclick": "pwa.referential.save(event,'referentialmenuteacher')"
},
{
"active": "",
"id": "referentialreferentialsettting",
"optionjsoneditor": {},
"groupinfo": "referentialsetting",
"btnsave": "Sauvegarder",
"onclick": "pwa.referential.save(event,'referentialmenuteacher')"
}
]
},
"en": {
"titre": "Gestion des référentiels",
"submenutitre": "Liste",
"submenuitems": [{
"active": "active",
"groupinfo": "menuAdmin.json",
"id": "referentialmenuadmin",
"btnsave": "Sauvegarder",
"onclick": "pwa.form.submit(event,'referentialmenuadmin',pwa.referentials.save)"
}, {
"active": "",
"id": "referentialmenuTeacher",
"groupinfo": "menuTeacher.json",
"btnsave": "Sauvegarder",
"onclick": "pwa.form.submit(event,'referentialmenuteacher',pwa.referentials.save)"
},
{
"active": "",
"id": "referentialusersetting",
"groupinfo": "usersetting.json"
},
{
"active": "",
"id": "referentialreferentialsettting",
"groupinfo": "referentialsetting.json"
}
]
}
}

View File

@ -1 +0,0 @@
{"fr":{"niv1":1,"niv2":12222222},"en":{"niv1":1,"niv2":2}}

View File

@ -1,60 +0,0 @@
{
"fr": {
"titre": "Information",
"submenutitre": "Vos paramétres",
"submenuitems": [{
"active": "active",
"id": "usersettingaccount",
"groupinfo": "Compte",
"publicinfo": "Informations publiques",
"pseudoplaceholder": "Votre pseudo",
"pseudodesc": "Votre pseudo",
"biographyplaceholder": "Quelque chose qui vous décrit",
"biographydesc": "Biographie",
"imguserupload": "Charger votre avatar",
"infoimgavatar": "Pour un bon résultat, utiliser une image carrée de 128px au format .jpg",
"btnsave": "Sauvegarder",
"onclick": "pwa.form.submit(event,'userpublicinfo',pwa.user.save)"
}, {
"active": "",
"id": "usersettingpassword",
"groupinfo": "Mot de passe"
},
{
"active": "",
"id": "usersettingprivacy",
"groupinfo": "Protection des données"
},
{
"active": "",
"id": "usersettingdelete",
"groupinfo": "Supprimer son compte"
}
]
},
"en": {
"titre": "Information",
"submenutitre": "Vos paramétres",
"submenuitems": [{
"active": "active",
"id": "usersettingaccount",
"groupinfo": "Compte"
}, {
"active": "",
"id": "usersettingpassword",
"groupinfo": "Mot de passe"
},
{
"active": "",
"id": "usersettingprivacy",
"groupinfo": "Protection des données"
},
{
"active": "",
"id": "usersettingdelete",
"groupinfo": "Supprimer son compte"
}
]
}
}

View File

@ -1,21 +0,0 @@
[
{
"idfield": "uuid",
"desc": { "fr": "identifiant de l'action", "en": "action id" },
"multilangue": false,
"required": true,
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "desc",
"required": true,
"multilangue": true,
"desc": {
"fr": "Description courte de cette modalité d'action",
"en": "Short Modality Description"
},
"type": "text",
"tpl": "questionInputVertical"
}
]

View File

@ -1,40 +0,0 @@
[
{
"idfield": "uuid",
"desc": { "fr": "identifiant de l'objet", "en": "object id" },
"multilangue": false,
"required": true,
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "desc",
"required": true,
"multilangue": true,
"desc": {
"fr": "Description courte de cette modalité d'objet",
"en": "Short Modality Description"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "desclong",
"multilangue": true,
"desc": {
"fr": "Description de cette modalité d'objet",
"en": "Modality Description"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "deschtml",
"desc": {
"fr": "Description en bloc html de cette modalité d'objet",
"en": "Html description of this object"
},
"type": "text",
"tpl": "questionTextarea"
}
]

View File

@ -1,41 +0,0 @@
[
{
"idfield": "uuid",
"desc": { "fr": "identifiant de l'objet", "en": "object id" },
"multilangue": false,
"required": true,
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "desc",
"required": true,
"multilangue": false,
"desc": {
"fr": "Description courte de cette modalité d'objet",
"en": "Short Modality Description"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "desclong",
"multilangue": true,
"desc": {
"fr": "Description de cette modalité d'objet",
"en": "Modality Description"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "deschtml",
"multilangue": true,
"desc": {
"fr": "Description en bloc html de cette modalité d'objet",
"en": "Html description of this object"
},
"type": "text",
"tpl": "questionTextarea"
}
]

View File

@ -1,96 +0,0 @@
[{
"idfield": "UUID",
"desc": {
"fr": "identifiant utilisateur",
"en": "user id"
},
"nouservisible": true,
"check": ["required", "unique"],
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "LOGIN",
"check": ["required", "unique"],
"desc": {
"fr": "login",
"en": "login"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "EMAIL",
"desc": {
"fr": "email",
"en": "email"
},
"type": "email",
"check": ["email", "unique"],
"placeholder": "@",
"tpl": "questionInputVertical"
},
{
"idfield": "NAME",
"desc": {
"fr": "Nom",
"en": "Name"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "NICKNAME",
"desc": {
"fr": "Prénom",
"en": "Nickname"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "PSEUDO",
"desc": {
"fr": "pseudo",
"en": "pseudo"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"nouserupdate": true,
"idfield": "DATE_CREATE",
"desc": {
"fr": "Date de création",
"en": "Create Date"
},
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"tpl": "questionInputVertical"
},
{
"nouserupdate": true,
"idfield": "DATE_UPDATE",
"desc": {
"fr": "Date mise à jour",
"en": "Update date"
},
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"tpl": "questionInputVertical"
},
{
"nouserupdate": true,
"idfield": "DATE_LASTLOGIN",
"desc": {
"fr": "Date de derniére connexion",
"en": "Last date login"
},
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"tpl": "questionInputVertical"
}
]

View File

@ -1,54 +0,0 @@
[{
"idfield": "UUID",
"desc": {
"fr": "identifiant utilisateur",
"en": "user id"
},
"nouservisible": true,
"check": ["required"],
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "LOGIN",
"desc": {
"fr": "Login",
"en": "Login"
},
"multilangue": false,
"required": true,
"nouserupdate": true,
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "PASSWORD",
"required": true,
"desc": {
"fr": "Mot de passe actuel",
"en": "Current password"
},
"type": "password",
"tpl": "questionInputVertical"
},
{
"idfield": "PSNEW",
"required": true,
"check": ["password"],
"desc": {
"fr": "Nouveau mot de passe",
"en": "New password"
},
"type": "password",
"tpl": "questionInputVertical"
},
{
"idfield": "PSWNEWBIS",
"desc": {
"fr": "Confirmation de mot de passe",
"en": "Password confirmation"
},
"type": "password",
"tpl": "questionInputVertical"
}
]

View File

@ -1,96 +0,0 @@
[{
"idfield": "UUID",
"desc": {
"fr": "identifiant utilisateur",
"en": "user id"
},
"nouservisible": true,
"check": ["required", "unique"],
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "LOGIN",
"check": ["required", "unique"],
"desc": {
"fr": "login",
"en": "login"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "EMAIL",
"desc": {
"fr": "email",
"en": "email"
},
"type": "email",
"check": ["email", "unique"],
"placeholder": "@",
"tpl": "questionInputVertical"
},
{
"idfield": "NAME",
"desc": {
"fr": "Nom",
"en": "Name"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "NICKNAME",
"desc": {
"fr": "Prénom",
"en": "Nickname"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "PSEUDO",
"desc": {
"fr": "pseudo",
"en": "pseudo"
},
"type": "text",
"tpl": "questionInputVertical"
},
{
"nouserupdate": true,
"idfield": "DATE_CREATE",
"desc": {
"fr": "Date de création",
"en": "Create Date"
},
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"tpl": "questionInputVertical"
},
{
"nouserupdate": true,
"idfield": "DATE_UPDATE",
"desc": {
"fr": "Date mise à jour",
"en": "Update date"
},
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"tpl": "questionInputVertical"
},
{
"nouserupdate": true,
"idfield": "DATE_LASTLOGIN",
"desc": {
"fr": "Date de derniére connexion",
"en": "Last date login"
},
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"tpl": "questionInputVertical"
}
]

View File

@ -1,108 +0,0 @@
[{
"idfield": "UUID",
"desc": {
"fr": "identifiant de l'items",
"en": "item id"
},
"check": ["required", "unique"],
"type": "text",
"questioncollecte": "questioninput"
},
{
"idfield": "ETAT",
"check": ["required"],
"desc": {
"fr": "Etat",
"en": "Stat"
},
"type": "text",
"questioncollect": "questionselect",
"options": [{
"uuid": "available",
"desc": {
"fr": "Disponible",
"en": "Available"
}
},
{
"uuid": "unavailable",
"desc": {
"fr": "Indisponible",
"en": "Unavailable"
}
}
]
},
{
"idfield": "DESC",
"desc": {
"fr": "Description courte",
"en": "Short description"
},
"questioncollecte": "questioninput"
},
{
"idfield": "DESCLONG",
"desc": {
"fr": "Descrition longue",
"en": "Long description"
},
"questioncollecte": "questioninput"
},
{
"idfield": "URL",
"desc": {
"fr": "URL",
"en": "URL"
},
"desclong": {
"fr": "Lien vers une page de détail de l'items",
"en": "Link to a web page that describe item"
},
"questioncollecte": "questioninput"
},
{
"idfield": "PRICETTC",
"desc": {
"fr": "Prix TTC en cents",
"en": "VAT Price in cents"
},
"check": ["isInt"],
"desclong": {
"fr": "Prix TTC exprimé en cents Prix x 100",
"en": "Price including Tax x 100"
}
},
{
"idfield": "CARACTERES",
"desc": {
"fr": "Objet contennat des caractéres pour mettre une mise en forme",
"en": " Contain list of characteristics to style "
},
"desclong": {
"fr": "Stockage d'information pour décricre des formulaires",
"en": ""
}
},
{
"idfield": "DATE_CREATE",
"desc": {
"fr": "Date de création",
"en": "Create Date"
},
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"questioncollecte": "questioninput"
}, {
"idfield": "DATE_UPDATE",
"desc": {
"fr": "Date mise à jour",
"en": "Update date"
},
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"questioncollecte": "questioninput"
}
]

View File

@ -1,48 +0,0 @@
[{
"idfield": "UUID",
"desc": {
"fr": "identifiant utilisateur",
"en": "user id"
},
"nouservisible": true,
"check": ["required", "unique"],
"type": "text",
"tpl": "questionInputVertical"
},
{
"nouserupdate": "!(['ADMIN','MANAGER'].includes(contexte.profil))",
"check": ["required"],
"idfield": "appsdiagimmoprofil",
"desc": {
"fr": "Droits"
},
"desclong": {
"fr": "USER ne peut voir que ses informations, MANAGER voit tout le monde et peut modifier les informations, ADMIN accede à tout et peut modifier "
},
"default": "USER",
"values": "profile",
"type": "text",
"tpl": "questionSelect"
},
{
"idfield": "role",
"desc": {
"fr": "Rôle",
"en": "Role"
},
"default": "Autre",
"values": "role",
"tpl": "questionSelect"
},
{
"idfield": "manypseudo",
"desc": {
"fr": "Liste des noms touvés dans liciel séparé par , "
},
"desclong": {
"fr": "Permet de regrouper plusieurs noms sous ce login"
},
"type": "text",
"tpl": "questionInputVertical"
}
]

View File

@ -1,231 +0,0 @@
[{
"idfield": "UUID",
"nouserupdate": true,
"nouservisible": true,
"desc": {
"fr": "identifiant utilisateur",
"en": "user id"
},
"desclong": {
"fr": "Identifiant unique généré via UUID v4",
"en": "unique Id from a UUID v4"
},
"info": {
"fr": "<p> L'usage d'UUID v4 permet de générer un code unique sans centralisation, car il est basé sur un timestamp et une clé crypto ce qui donne un code du type 7d8291c0-e137-11e8-9f7b-1dc8e57bed33 </p>",
"en": "<p> UUID v4 allow a client to generate a unique code without centralisation, base on a timestamp and a salt it looks like 7d8291c0-e137-11e8-9f7b-1dc8e57bed33</p>"
},
"check": ["required", "unique"],
"type": "text",
"tpl": "input"
},
{
"idfield": "LOGIN",
"nouserupdate": true,
"check": ["required", "unique"],
"desc": {
"fr": "login",
"en": "login"
},
"type": "text",
"tpl": "input",
"info": {
"fr": "<p>Le login doit être unique sur une instance d'apxtrib.</p><p> Pour échanger en dehors d'une instance apxtrib on utilise la clé public du user ou pour un humain login@apxtrib.domain.xx avec le nom du domaine qui heberge l'instance</p><p> Ou encore login@domain.xx tout domain.xx utilisé pour heberger un espace web client /tribeid/www/</p>",
"en": "<p>Login have to be unique into an apxtrib instance</p><p> To exchange outside of an apxtrib instance, we use PublicKey or login@apxtrib.domain.xx or login@domainclient.xx where domain.xx is a apxtrib name server on internet and domain.xx is a tribeid name where a /tribeid/www is available on the net.</p>"
}
},
{
"idfield": "BIOGRAPHY",
"desc": {
"fr": "Vous en quelques mots",
"en": "Few words"
},
"placeholder": {
"fr": "",
"en": ""
},
"rows": 2,
"tpl": "textarea"
},
{
"nouserupdate": true,
"idfield": "PUBLICKEY",
"desc": {
"fr": "Votre clé public pour ce compte",
"en": "Your public key for this uuid"
},
"info": {
"fr": "<p>Cette clé est générée par votre navigateur, garder précisuesement votre clé privée que seule vous connaissez. En cas de perte de cette clé tous vos actifs seront perdus.</p><p>Cette méthode nous permet de vous garantir un contrôle total décentralisé.</p>",
"en": "<p>This key was generated by your browser, keep the private key related to this public key.</p><p>We garanty your total control by this way</p>."
},
"tpl": "textarea"
},
{
"idfield": "IMGAVATAR",
"tpl": "inputimg",
"altimg": "image avatar",
"classimg": "rounded-circle img-responsive mt-2",
"width": 128,
"height:"
128,
"classdivupload": "mt-2",
"classbtn": "btn-primary",
"desc": {
"fr": "changer votre avatar",
"en": "upload an avatar"
},
"info": {
"fr": "Pour un meilleur rendu, une mage carré de 128pc en foat jpg",
"en": "For best results, use an image at least 128px by 128px in .jpg format"
},
},
{
"idfield": "EMAIL",
"desc": {
"fr": "email",
"en": "email"
},
"tpl": "input",
"type": "email",
"check": ["emailadress", "unique"],
"placeholder": {
"fr": "#@",
"en": "@"
}
},
{
"idfield": "NAME",
"desc": {
"fr": "Nom",
"en": "Name"
},
"tpl": "input",
"type": "text"
},
{
"idfield": "NICKNAME",
"desc": {
"fr": "Prénom",
"en": "Nickname"
},
"tpl": "input",
"type": "text"
},
{
"idfield": "PSEUDO",
"desc": {
"fr": "pseudo",
"en": "pseudo"
},
"info": {
"fr": "<p>Nom avec lequel vous souhaitez qu'on vous reconnaisse sur l'instance de l'apxtrib </p><p>Attention ce nom n'est unique que sur une instance d'apxtrib. Un même speudo peut-être utilisé sur un autre serveur pour garantir l'identité vérifié pseudo@ domaine de rattachement.</p>",
"en": "<p>Carrefull a pseudo is unique into an instance of apxtrib to be sure to contact the right person check pseudo@ domain</p>.<p> Pseudo can be changed that is not the case of login.</p>"
},
"tpl": "input",
"type": "text"
},
{
"idfield": "ADDRESS1",
"desc": {
"fr": "Adresse",
"en": "Address"
},
"tpl": "input",
"type": "text",
"placeholder": {
"fr": "1 chemin du paradis",
"123 Main St"
}
},
{
"idfield": "ADDRESS2",
"desc": {
"fr": "Adresse 2",
"en": "Address 2"
},
"tpl": "input",
"type": "text",
"placeholder": {
"fr": "Appartement B",
"Apt B"
}
},
{
"idfield": "CITY",
"desc": {
"fr": "Ville ",
"en": "CITY"
},
"tpl": "input",
"type": "text"
},
{
"idfield": "ZIP",
"desc": {
"fr": "Code Postal",
"en": "ZIP"
},
"tpl": "input",
"type": "text"
},
{
"idfield": "COUNTRY",
"desc": {
"fr": "Pays",
"en": "Country"
},
"tpl": "input",
"type": "text"
},
{
"nouserupdate": true,
"idfield": "DATE_CREATE",
"desc": {
"fr": "Date de création",
"en": "Create Date"
},
"tpl": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')"
},
{
"nouserupdate": true,
"idfield": "DATE_UPDATE",
"desc": {
"fr": "Date mise à jour",
"en": "Update date"
},
"tpl": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')"
},
{
"nouserupdate": true,
"idfield": "DATE_LASTLOGIN",
"desc": {
"fr": "Date de derniére connexion",
"en": "Last date login"
},
"tpl": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')"
},
{
"idfield": "ACCESSRIGHTS",
"nouserupdate": true,
"desc": {
"fr": "Vos droits d'accès",
"en": "Your access rights"
},
"default": {
"app": {},
"data": {
"tribeidname": {
"users": "O"
}
}
},
"tpl": "jsoneditor"
}
]

View File

@ -1,231 +0,0 @@
[{
"idfield": "UUID",
"nouserupdate": true,
"nouservisible": true,
"desc": {
"fr": "identifiant utilisateur",
"en": "user id"
},
"desclong": {
"fr": "Identifiant unique généré via UUID v4",
"en": "unique Id from a UUID v4"
},
"info": {
"fr": "<p> L'usage d'UUID v4 permet de générer un code unique sans centralisation, car il est basé sur un timestamp et une clé crypto ce qui donne un code du type 7d8291c0-e137-11e8-9f7b-1dc8e57bed33 </p>",
"en": "<p> UUID v4 allow a client to generate a unique code without centralisation, base on a timestamp and a salt it looks like 7d8291c0-e137-11e8-9f7b-1dc8e57bed33</p>"
},
"check": ["required", "unique"],
"type": "text",
"tpl": "input"
},
{
"idfield": "LOGIN",
"nouserupdate": true,
"check": ["required", "unique"],
"desc": {
"fr": "login",
"en": "login"
},
"type": "text",
"tpl": "input",
"info": {
"fr": "<p>Le login doit être unique sur une instance d'apxtrib.</p><p> Pour échanger en dehors d'une instance apxtrib on utilise la clé public du user ou pour un humain login@apxtrib.domain.xx avec le nom du domaine qui heberge l'instance</p><p> Ou encore login@domain.xx tout domain.xx utilisé pour heberger un espace web client /tribeid/www/</p>",
"en": "<p>Login have to be unique into an apxtrib instance</p><p> To exchange outside of an apxtrib instance, we use PublicKey or login@apxtrib.domain.xx or login@domainclient.xx where domain.xx is a apxtrib name server on internet and domain.xx is a tribeid name where a /tribeid/www is available on the net.</p>"
}
},
{
"idfield": "BIOGRAPHY",
"desc": {
"fr": "Vous en quelques mots",
"en": "Few words"
},
"placeholder": {
"fr": "",
"en": ""
},
"rows": 2,
"tpl": "textarea"
},
{
"nouserupdate": true,
"idfield": "PUBLICKEY",
"desc": {
"fr": "Votre clé public pour ce compte",
"en": "Your public key for this uuid"
},
"info": {
"fr": "<p>Cette clé est générée par votre navigateur, garder précisuesement votre clé privée que seule vous connaissez. En cas de perte de cette clé tous vos actifs seront perdus.</p><p>Cette méthode nous permet de vous garantir un contrôle total décentralisé.</p>",
"en": "<p>This key was generated by your browser, keep the private key related to this public key.</p><p>We garanty your total control by this way</p>."
},
"tpl": "textarea"
},
{
"idfield": "IMGAVATAR",
"tpl": "inputimg",
"altimg": "image avatar",
"classimg": "rounded-circle img-responsive mt-2",
"width": 128,
"height:"
128,
"classdivupload": "mt-2",
"classbtn": "btn-primary",
"desc": {
"fr": "changer votre avatar",
"en": "upload an avatar"
},
"info": {
"fr": "Pour un meilleur rendu, une mage carré de 128pc en foat jpg",
"en": "For best results, use an image at least 128px by 128px in .jpg format"
},
},
{
"idfield": "EMAIL",
"desc": {
"fr": "email",
"en": "email"
},
"tpl": "input",
"type": "email",
"check": ["emailadress", "unique"],
"placeholder": {
"fr": "#@",
"en": "@"
}
},
{
"idfield": "NAME",
"desc": {
"fr": "Nom",
"en": "Name"
},
"tpl": "input",
"type": "text"
},
{
"idfield": "NICKNAME",
"desc": {
"fr": "Prénom",
"en": "Nickname"
},
"tpl": "input",
"type": "text"
},
{
"idfield": "PSEUDO",
"desc": {
"fr": "pseudo",
"en": "pseudo"
},
"info": {
"fr": "<p>Nom avec lequel vous souhaitez qu'on vous reconnaisse sur l'instance de l'apxtrib </p><p>Attention ce nom n'est unique que sur une instance d'apxtrib. Un même speudo peut-être utilisé sur un autre serveur pour garantir l'identité vérifié pseudo@ domaine de rattachement.</p>",
"en": "<p>Carrefull a pseudo is unique into an instance of apxtrib to be sure to contact the right person check pseudo@ domain</p>.<p> Pseudo can be changed that is not the case of login.</p>"
},
"tpl": "input",
"type": "text"
},
{
"idfield": "ADDRESS1",
"desc": {
"fr": "Adresse",
"en": "Address"
},
"tpl": "input",
"type": "text",
"placeholder": {
"fr": "1 chemin du paradis",
"123 Main St"
}
},
{
"idfield": "ADDRESS2",
"desc": {
"fr": "Adresse 2",
"en": "Address 2"
},
"tpl": "input",
"type": "text",
"placeholder": {
"fr": "Appartement B",
"Apt B"
}
},
{
"idfield": "CITY",
"desc": {
"fr": "Ville ",
"en": "CITY"
},
"tpl": "input",
"type": "text"
},
{
"idfield": "ZIP",
"desc": {
"fr": "Code Postal",
"en": "ZIP"
},
"tpl": "input",
"type": "text"
},
{
"idfield": "COUNTRY",
"desc": {
"fr": "Pays",
"en": "Country"
},
"tpl": "input",
"type": "text"
},
{
"nouserupdate": true,
"idfield": "DATE_CREATE",
"desc": {
"fr": "Date de création",
"en": "Create Date"
},
"tpl": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')"
},
{
"nouserupdate": true,
"idfield": "DATE_UPDATE",
"desc": {
"fr": "Date mise à jour",
"en": "Update date"
},
"tpl": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')"
},
{
"nouserupdate": true,
"idfield": "DATE_LASTLOGIN",
"desc": {
"fr": "Date de derniére connexion",
"en": "Last date login"
},
"tpl": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')"
},
{
"idfield": "ACCESSRIGHTS",
"nouserupdate": true,
"desc": {
"fr": "Vos droits d'accès",
"en": "Your access rights"
},
"default": {
"app": {},
"data": {
"tribeidname": {
"users": "O"
}
}
},
"tpl": "jsoneditor"
}
]

View File

@ -1,93 +0,0 @@
[{
"idfield": "UUID",
"desc": "identifiant utilisateur",
"nouservisible": true,
"check": [
"required",
"unique"
],
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "LOGIN",
"check": [
"required",
"unique"
],
"desc": "login",
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "EMAIL",
"desc": "email",
"type": "email",
"check": [
"emailadress",
"unique"
],
"placeholder": "@",
"tpl": "questionInputVertical"
},
{
"idfield": "NAME",
"desc": "Nom",
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "NICKNAME",
"desc": "Prénom",
"type": "text",
"tpl": "questionInputVertical"
},
{
"idfield": "PSEUDO",
"desc": "pseudo",
"type": "text",
"tpl": "questionInputVertical"
},
{
"nouserupdate": true,
"idfield": "DATE_CREATE",
"desc": "Date de création",
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"tpl": "questionInputVertical"
},
{
"nouserupdate": true,
"idfield": "DATE_UPDATE",
"desc": "Date mise à jour",
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"tpl": "questionInputVertical"
},
{
"nouserupdate": true,
"idfield": "DATE_LASTLOGIN",
"desc": "Date de derniére connexion",
"type": "date",
"format": "YYYY-MM-DD",
"default": "moment(new Date()).format('YYYY-MM-DD')",
"tpl": "questionInputVertical"
},
{
"idfield": "accessrights",
"type": "json",
"nouserupdate": true,
"desc": "Vos droits d'accès",
"default": {
"app": {},
"data": {
"tribeidname": {
"users": "O"
}
}
},
"tpl": "jsoneditor"
}
]

View File

@ -1,3 +0,0 @@
{
"phc@ndda.fr": "admin"
}

View File

@ -1,3 +0,0 @@
{
"admin": "admin"
}

View File

@ -1,19 +0,0 @@
{
"admin": [
"admin",
"phc@ndda.fr",
"$2b$10$hFV/33UixB3Cn.XzLIhmTeRYU2XThnxYuwCVIifwQ7v/yCtRLIsuq",
{
"app": {
"apxtrib:webapp": "admin"
},
"data": {
"apxtrib": {
"users": "CRUDO",
"referentials": "CRUDO"
}
}
},
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHBpcmF0aW9uIjoiMjAyMS0wOS0wMlQxMjo0ODowMS41OTNaIiwiVVVJRCI6IjEyM2FiYyJ9.4daX42iXqoblGL0c1Ga-hs5tGIoJEuWBSKqCayA-qNk"
]
}

View File

@ -1,48 +0,0 @@
<html data-tribeid="apxtrib" data-website="webapp" data-nametpl="app" data-pagename="index_fr" data-pageneedauthentification="false" data-pageredirectforauthentification="fullscreen_auth" data-urlbackoffice="apxtrib.ndda.fr" lang="fr" data-env="prod" data-version="1640518264045">
<head><!--head -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="author" content="">
<meta name="email" content="">
<meta name="keywords" content="">
<title>Need-Data manager></title>
<link rel="icon" type="image/png" href="static&#x2F;img&#x2F;icons&#x2F;iconX74x74.png">
<link rel="manifest" href="manifest.json">
<link rel="stylesheet" type="text/css" href="static&#x2F;fonts&#x2F;icofont&#x2F;icofont.min.css">
<link rel="stylesheet" type="text/css" href="css&#x2F;app&#x2F;styles.css">
<!-- /head-->
</head>
<body>
<div class="wrapper"> <!-- div class="wrapper" -->
<nav id="sidebar" class="sidebar"></nav>
<div class="main">
<nav id ="navbar" class="navbar navbar-expand navbar-light navbar-bg"></nav>
<main class="content">
<div class="container-fluid p-0" id="maincontent"> <!-- div id="maincontent" class="container-fluid p-0" -->
<p>Content when js is desactivated</p>
<!--/div-->
</div>
</main>
<footer class="footer">
<div class="container-fluid">
<div class="row text-muted">
<div class="col-6 text-start">
<p class="mb-0">
<a href="" class="text-muted"><strong></strong></a> &copy;
</p>
</div>
<div class="col-6 text-end">
<ul class="list-inline">
</ul>
</div>
</div>
</div>
</footer>
</div>
<!-- /div -->
</div>
<script src='js/simplebar.min.js'></script><script src='js/feather.min.js'></script><script src='js/bootstrap.js'></script><script src='js/axios.min.js'></script><script src='js/mustache.min.js'></script><script src='js/Checkjson.js'></script><script src='js/auth.js'></script><script src='js/state.js'></script><script src='js/main.js'></script><script src='js/notification.js'></script></body></html>

View File

@ -1 +0,0 @@
[data-simplebar]{position:relative;flex-direction:column;flex-wrap:wrap;justify-content:flex-start;align-content:flex-start;align-items:flex-start}.simplebar-wrapper{overflow:hidden;width:inherit;height:inherit;max-width:inherit;max-height:inherit}.simplebar-mask{direction:inherit;position:absolute;overflow:hidden;padding:0;margin:0;left:0;top:0;bottom:0;right:0;width:auto!important;height:auto!important;z-index:0}.simplebar-offset{direction:inherit!important;box-sizing:inherit!important;resize:none!important;position:absolute;top:0;left:0;bottom:0;right:0;padding:0;margin:0;-webkit-overflow-scrolling:touch}.simplebar-content-wrapper{direction:inherit;box-sizing:border-box!important;position:relative;display:block;height:100%;width:auto;max-width:100%;max-height:100%;scrollbar-width:none;-ms-overflow-style:none}.simplebar-content-wrapper::-webkit-scrollbar,.simplebar-hide-scrollbar::-webkit-scrollbar{width:0;height:0}.simplebar-content:after,.simplebar-content:before{content:' ';display:table}.simplebar-placeholder{max-height:100%;max-width:100%;width:100%;pointer-events:none}.simplebar-height-auto-observer-wrapper{box-sizing:inherit!important;height:100%;width:100%;max-width:1px;position:relative;float:left;max-height:1px;overflow:hidden;z-index:-1;padding:0;margin:0;pointer-events:none;flex-grow:inherit;flex-shrink:0;flex-basis:0}.simplebar-height-auto-observer{box-sizing:inherit;display:block;opacity:0;position:absolute;top:0;left:0;height:1000%;width:1000%;min-height:1px;min-width:1px;overflow:hidden;pointer-events:none;z-index:-1}.simplebar-track{z-index:1;position:absolute;right:0;bottom:0;pointer-events:none;overflow:hidden}[data-simplebar].simplebar-dragging .simplebar-content{pointer-events:none;user-select:none;-webkit-user-select:none}[data-simplebar].simplebar-dragging .simplebar-track{pointer-events:all}.simplebar-scrollbar{position:absolute;left:0;right:0;min-height:10px}.simplebar-scrollbar:before{position:absolute;content:'';background:#000;border-radius:7px;left:2px;right:2px;opacity:0;transition:opacity .2s linear}.simplebar-scrollbar.simplebar-visible:before{opacity:.5;transition:opacity 0s linear}.simplebar-track.simplebar-vertical{top:0;width:11px}.simplebar-track.simplebar-vertical .simplebar-scrollbar:before{top:2px;bottom:2px}.simplebar-track.simplebar-horizontal{left:0;height:11px}.simplebar-track.simplebar-horizontal .simplebar-scrollbar:before{height:100%;left:2px;right:2px}.simplebar-track.simplebar-horizontal .simplebar-scrollbar{right:auto;left:0;top:2px;height:7px;min-height:0;min-width:10px;width:auto}[data-simplebar-direction=rtl] .simplebar-track.simplebar-vertical{right:auto;left:0}.hs-dummy-scrollbar-size{direction:rtl;position:fixed;opacity:0;visibility:hidden;height:500px;width:500px;overflow-y:hidden;overflow-x:scroll}.simplebar-hide-scrollbar{position:fixed;left:0;visibility:hidden;overflow-y:scroll;scrollbar-width:none;-ms-overflow-style:none}

View File

@ -1,169 +0,0 @@
<html data-tribeid="apxtrib" data-website="webapp" data-nametpl="fullscreen" data-pagename="auth_fr" data-pageneedauthentification="false" data-pageredirectforauthentification="fullscreen_auth" data-urlbackoffice="apxtrib.ndda.fr" lang="fr" data-env="prod" data-version="1640518263426">
<head><!--head -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="author" content="">
<meta name="email" content="">
<meta name="keywords" content="">
<title>apxtrib></title>
<link rel="stylesheet" type="text/css" href="static&#x2F;fonts&#x2F;icofont&#x2F;icofont.min.css">
<link rel="stylesheet" type="text/css" href="css&#x2F;fullscreen&#x2F;styles.css">
<!-- /head-->
</head>
<body data-theme="dark" data-layout="fluid" data-sidebar-position="left" data-sidebar-layout="default">
<main class="d-flex w-100 h-100"><!-- main class="d-flex w-100 h-100" -->
<div class="container d-flex flex-column">
<div class="row vh-100">
<div class="col-sm-10 col-md-8 col-lg-6 mx-auto d-table h-100">
<div class="d-table-cell align-middle"><!--div class="d-table-cell align-middle"-->
<div id="signin">
<div class="text-center mt-4">
<h1 class="h2">Need-Data</h1>
<p class="lead">
Votre hébergement apxtrib en toute confidentialité.
</p>
</div>
<div class="card">
<div class="card-body">
<div class="m-sm-4">
<div class="text-center">
<img src="static/img/logo/ndda.png" alt="logo apxtrib" class="img-fluid" width="132" height="132" />
</div>
<form>
<div class="mb-3">
<label class="form-label">Identifiant</label>
<input class="form-control form-control-lg" type="text" name="login" value="adminapxtrib" placeholder="Votre identifiant (login ou clé public)" />
</div>
<div class="mb-3">
<label class="form-label">Mot de passe</label>
<input class="form-control form-control-lg" type="password" name="password"
value="Trze3aze!" placeholder="Mot de passe ou hash sur clé public" />
<small>
<a onclick="pwa.auth.route('#resetpsw');return false;">Mot de passe oublié?</a>
</small>
</div>
<div>
<label class="form-check">
<input class="form-check-input" type="checkbox" value="rememberme" name="rememberme" checked>
<span class="form-check-label">
Se souvenir de moi sur ce navigateur
</span>
</label>
</div>
<div class="text-center mt-3">
<button
class="btn btn-lg btn-primary"
onclick="pwa.auth.login();return false;"
data-msgok="Bienvenu dans votre espace."
data-msgko="Désolé, vos identifiants ne sont pas valides! Au bout de 3 echecs, vous devrez attendre 1 minute entre chaque tentative."
data-routeto="app_index_fr.html"
>S'authentifier
</button>
<p class="msginfo"></p>
</div>
</form>
<p class="text-center">
<small>
<a onclick="pwa.auth.route(&#39;#register&#39;);return false;" >Rejoindre un espace</a>
</small>
</p>
</div>
</div>
</div>
</div>
<div id="resetpsw" class="d-none">
<div class="text-center mt-4">
<h1 class="h2">Mot de passe oublié</h1>
<p class="lead">
Indiquez votre email. Si vous n'avez pas indiqué d'email, vos données sont definitivement perdues, c'est le prix de votre anonymat.
</p>
</div>
<div class="card">
<div class="card-body">
<div class="m-sm-4">
<form>
<div class="mb-3">
<label class="form-label">Email</label>
<input class="form-control form-control-lg" type="email" name="email" placeholder="indiquez votre email">
</div>
<div class="text-center mt-3">
<button
onclick="pwa.auth.forget();return false;"
data-msgok="Une email vous a été envoyé"
data-msgko="Lien impossible à envoyer "
class="btn btn-lg btn-primary">
Recevoir un lien temporaire
</button>
<p class="msginfo"></p>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="register" class="d-none">
<div class="d-table-cell align-middle">
<div class="text-center mt-4">
<h1 class="h2">S'inscrire à votre communauté</h1>
<p class="lead">
Vous devez disposez du nom de la communauté qui vous invite à ouvrir un compte chez elle.<br> Pour créer une communauté, sur cet hébergement: <a href='mailto:contact@need-data.com'>contact@need-data.com</a>.<br> En savoir plus sur <a href='https://apxtrib.org/anonymat_avec_apixppress.html'>Anomymat & apxtrib</a>.
</p>
</div>
<div class="card">
<div class="card-body">
<div class="m-sm-4">
<form>
<div class="mb-3">
<label class="form-label">Nom de communauté</label>
<input class="form-control form-control-lg" type="text" name="company" placeholder="Nom communiqué par la personne qui vous invite.">
</div>
<div class="text-center mt-3">
<button
onclick="pwa.auth.autologin();return false;"
class="btn btn-lg btn-primary">
Génerer une paire<br> de clé public/privée
</button>
</div>
<div class="mb-3">
<label class="form-label">Votre identifiant</label>
<input class="form-control form-control-lg" type="text" name="login" placeholder="login ou clé public">
</div>
<div class="mb-3">
<label class="form-label">Mot de passe</label>
<input class="form-control form-control-lg" type="password" name="password" placeholder="Mot de passe ou hash sur clé public">
</div>
<div class="mb-3">
<label class="form-label">Email (optionel)</label>
<input class="form-control form-control-lg" type="email" name="email" placeholder="Sans email impossible de ré-initialiser son compte">
</div>
<div class="text-center mt-3">
<button
onclick="pwa.auth.register();return false;"
data-msgok="Votre compte a bien été créé"
data-msgko="Désolé impossible de créer le compte"
class="btn btn-lg btn-primary">
S'enregistrer
</button>
<p class="msginfo"></p>
<p class="text-center">
<small>
<a onclick="pwa.auth.route(&#39;#signin&#39;);return false;" >S'authentifier</a>
</small>
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- /div-->
</div>
</div>
</div>
</div>
<!-- /main -->
</main>
<script src='js/simplebar.min.js'></script><script src='js/feather.min.js'></script><script src='js/bootstrap.js'></script><script src='js/axios.min.js'></script><script src='js/mustache.min.js'></script><script src='js/Checkjson.js'></script><script src='js/auth.js'></script><script src='js/state.js'></script><script src='js/main.js'></script><script src='js/notification.js'></script><script src='js/auth.js'></script></body></html>

View File

@ -1,216 +0,0 @@
"use strict";
var pwa = pwa || {};
/*
Manage user authentification and registration
________________________
pwa.auth.route()
manage from state.json route if authenticated or not
redirect public page or app page
________________________
pwa.auth.screenlogin()
show login modal
________________________
pwa.auth.getlinkwithoutpsw()
special get with token and uuid workeable for 24h this link is une onetime
_________________________
pwa.auth.isAuthenticate()
test if token is still ok or not return false/true
_________________________
pwa.auth.authentification({LOGIN,PASSWORD})
if ok => load pwa.state.data.app .headers .userlogin
_________________________
pwa.auth.login()
Manage login modal to get login psw value and submit it to pwa.auth.authentification()
_________________________
pwa.auth.logout()
Remove localstorage and reload
_________________________
pwa.auth.register()
@TODO
__________________________
pwa.auth.forgetpsw()
Request to send an email with a unique get link to access from this link to the app
*/
/*MODULEJS*/
//--##
pwa.auth = {};
// Refresh browser state if exist else get pwa.state defaults
//pwa.state.ready( pwa.auth.check );
pwa.auth.Checkjson = () => {
if( pwa.state.data.login.isAuthenticated ) {
if( !pwa.auth.isAuthenticate() ) {
// Then reinit local storage and refresh page
pwa.state.data.login.isAuthenticated = false;
pwa.state.save();
//alert( 'reload page cause no more auth' )
window.location.reload();
};
}
};
pwa.auth.route = ( destination ) => {
console.log( 'auth.route to', destination );
//if check Authenticated && exist #signin button[data-routeto] then redirect browser to button[data-routeto]
//else manage component action auth
if( pwa.state && pwa.state.data && pwa.state.data.login && pwa.state.data.login.isAuthenticated ) {
if( destination )
window.location.pathname = `${pwa.state.data.ctx.urlbase}/${destination}`;
} else {
[ "#signin", "#resetpsw", "#register" ].forEach( e => {
if( e == destination ) {
document.querySelector( e )
.classList.remove( 'd-none' );
} else {
document.querySelector( e )
.classList.add( 'd-none' );
}
} )
}
}
pwa.auth.isAuthenticate = async function () {
// in any request, if middleware isAuthenticated return false
// then headers Xuuid is set to 1
// then try pwa.auth.isAuthenticate if rememberMe auto reconnect
// if jwt is ok then return true in other case => false
// this is the first test then depending of action see ACCESSRIGHTS of user
console.log( 'lance isauth', {
headers: pwa.state.data.headers.xpaganid
} )
//alert( 'uuid ' + pwa.state.data.headers.xpaganid )
console.log( `https://${pwa.state.data.ctx.urlbackoffice}/users/isauth`, {
headers: pwa.state.data.headers
} )
try {
const repisauth = await axios.get( `https://${pwa.state.data.ctx.urlbackoffice}/users/isauth`, {
headers: pwa.state.data.headers
} )
console.log( repisauth )
console.log( 'isAauthenticate: yes' )
return true;
} catch ( err ) {
if( err.response ) { console.log( "response err ", err.response.data ) }
if( err.request ) { console.log( "request err", err.request ) }
console.log( 'isAuthenticate: no' )
pwa.state.data.headers.xpaganid = "1";
if( pwa.state.data.login.rememberMe.login ) {
if( await pwa.auth.authentification( pwa.state.data.login.rememberMe ) ) {
return await pwa.auth.isAuthenticate();
};
}
return false;
}
};
pwa.auth.authentification = async function ( data ) {
// Core client function to chech auth from login & psw
// In case of 403 error lauch pwa.authentification(pwa.app.rememberMe)
// in case of sucess update paw.state.data.login
console.groupCollapsed( "Post Authentification for standard on : https://" + pwa.state.data.ctx.urlbackoffice + "/users/login param data", data )
console.log( 'header de login', pwa.state.data.headers )
let auth;
try {
auth = await axios.post( `https://${pwa.state.data.ctx.urlbackoffice }/users/login`, data, {
headers: pwa.state.data.headers
} );
console.log( "retour de login successfull ", auth );
//Maj variable globale authentifié
pwa.state.data.headers.xpaganid = auth.data.payload.data.UUID;
pwa.state.data.headers.xauth = auth.data.payload.data.TOKEN;
pwa.state.data.headers.xtribe = auth.data.payload.data.tribeid;
pwa.state.data.headers.xworkon = auth.data.payload.data.tribeid;
// Save local authentification uuid/token info user
pwa.state.data.login.user = auth.data.payload.data;
//request a refresh after a login
pwa.state.data.ctx.refreshstorage = true;
pwa.state.save();
//alert( 'pwa.state.save() fait avec uuid' + pwa.state.data.headers.xpaganid )
console.groupEnd();
return true;
} catch ( err ) {
if( err.response ) { console.log( "resp", err.response.data ) }
if( err.request ) { console.log( "req", err.request.data ) }
console.log( 'erreur de login reinit de rememberMe', err )
pwa.state.data.login.rememberMe = {};
document.querySelector( "#signin p.msginfo" )
.innerHTML = document.querySelector( "#signin [data-msgko]" )
.getAttribute( 'data-msgko' );
console.groupEnd();
return false;
}
};
pwa.auth.logout = function () {
console.log( "remove ", pwa.state.data.ctx.website );
localStorage.removeItem( pwa.state.data.ctx.website );
window.location.href = "/";
}
pwa.auth.login = async function () {
/*
Check login/psw
see auth.mustache & data_auth_lg.json for parameters
Context info used:
#signin p.msginfo contain message interaction with user
#signin data-msgok data-msgko
#signin button[data-routeto] is a redirection if authentification is successful
*/
document.querySelector( '#signin p.msginfo' )
.innerHTML = "";
const data = {
LOGIN: document.querySelector( "#signin input[name='login']" )
.value,
PASSWORD: document.querySelector( "#signin input[name='password']" )
.value
}
console.log( 'check password', Checkjson.test.password( "", data.PASSWORD ) )
if( data.LOGIN.length < 4 || !Checkjson.test.password( "", data.PASSWORD ) ) {
/*$("#loginpart p.msginfo")
.html("")
.fadeOut(2000)*/
document.querySelector( '#signin p.msginfo' )
.innerHTML = document.querySelector( '#signin [data-msgko]' )
.getAttribute( 'data-msgko' );
} else {
if( document.querySelector( "[name='rememberme']" )
.checked ) {
pwa.state.data.login.rememberMe = data;
}
if( await pwa.auth.authentification( data ) ) {
console.log( 'Authentification VALIDE' )
document.querySelector( '#signin p.msginfo' )
.innerHTML = document.querySelector( "#signin [data-msgok]" )
.getAttribute( 'data-msgok' );
//state l'état isAuthenticated et check la route
pwa.state.data.login.isAuthenticated = true;
pwa.state.save();
console.log( pwa.state.data.login )
console.log( 'Auth ok route to ', document.querySelector( '#signin button[data-routeto]' )
.getAttribute( 'data-routeto' ) );
pwa.auth.route( document.querySelector( '#signin button[data-routeto]' )
.getAttribute( 'data-routeto' ) );
}
}
};
pwa.auth.register = async function ( event ) {
event.preventDefault();
// gérer la cration du user
}
pwa.auth.forgetpsw = async function ( event ) {
event.preventDefault();
const tribeid = $( ".loginregister" )
.getAttribute( "data-tribeid" );
const email = $( '.forgetpsw .email' )
.val();
console.log( `Reinit email: ${email} for tribeid: ${tribeid}` )
try {
console.log( `https://${pwa.state.data.ctx.urlbackoffice }/users/getlinkwithoutpsw/${email}` )
const reinit = await axios.get( `https://${pwa.state.data.ctx.urlbackoffice }/users/getlinkwithoutpsw/${email}`, {
headers: pwa.state.data.headers
} )
$( "#forgetpswpart p.msginfo" )
.html( "Regardez votre boite email" );
return true;
} catch ( er ) {
console.log( "Pb d'accès au back check apiamaildigit" )
return false;
}
};

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,184 +0,0 @@
/*
This module have to be independant of any external package
it is shared between back and front and is usefull
to apply common check in front before sending it in back
can be include in project with
<script src="https://apiback.maildigit.fr/js/Checkjson.js"></script>
or with const Checkjson = require('../public/js/Checkjson.js')
*/
// --##
const Checkjson = {};
// each Checkjson.test. return true or false
Checkjson.test = {};
Checkjson.test.emailadress = ( ctx, email ) => {
const regExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return regExp.test( email );
};
/*
* @emaillist = "email1,email2, email3"
* it check if each eamil separate by , are correct
*/
Checkjson.test.emailadresslist = ( ctx, emaillist ) => {
//console.log(emaillist.split(','))
if( emaillist.length > 0 ) {
const emails = emaillist.split( ',' );
for( var i in emails ) {
//console.log(emails[i])
if( !Checkjson.test.emailadress( "", emails[ i ].trim() ) ) {
return false
}
}
};
return true;
};
Checkjson.test.password = ( ctx, pwd ) => {
const regExp = new RegExp(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&.])[A-Za-z\d$@$!%*?&.{}:|\s]{8,}/
);
return regExp.test( pwd );
};
Checkjson.test.required = ( ctx, val ) =>
val != null && val != 'undefined' && val.length > 0;
Checkjson.test.isNumber = ( ctx, n ) => typeof n === 'number';
Checkjson.test.isInt = ( ctx, n ) => n != '' && !isNaN( n ) && Math.round( n ) == n;
Checkjson.test.isFloat = ( ctx, n ) => n != '' && !isNaN( n ) && Math.round( n ) != n;
Checkjson.test.unique = ( ctx, val ) => {
if( ctx.list[ ctx.currentfield ] ) {
return !ctx.list[ ctx.currentfield ].includes( val );
} else {
console.log( 'ERR no list for field:' + ctx.currentfield );
return false;
}
};
Checkjson.test.isDateDay = ( ctx, dateDay ) => true;
/* Checkjson.test.filterInvalidInArray = (array, validate) =>
array ? array.filter(el => !validate(el)) : true;
// return true when every elements is valid
*/
Checkjson.test.postalCode = ( ctx, postalCode ) => {
if( postalCode.length == 0 ) return true;
const regExp = new RegExp( /(^\d{5}$)|(^\d{5}-\d{4}$)/ );
return regExp.test( postalCode );
};
/**
* PHONE
*/
Checkjson.test.phoneNumber = ( ctx, phoneNumber ) => {
if( phoneNumber.length == 0 ) return true;
phoneNumber = phoneNumber.trim()
.replace( /[- .]/g, '' )
//french number
const regExpfr = new RegExp( /^0[1-9][0-9]{9}$/ );
const regExpInternational = new RegExp( /^\+*(\d{3})*[0-9,\-]{8,}/ );
return regExpfr.test( phoneNumber ) || regExpInternational.test( phoneNumber );
};
/*
* @phonelist = "phone1,phone2,phone3"
* it check if each phone separate by , are correct
*/
Checkjson.test.phoneNumberlist = ( ctx, phonelist ) => {
//console.log(emaillist.split(','))
if( phonelist.length > 0 ) {
const phones = phonelist.split( ',' );
for( var i in phones ) {
//console.log(emails[i])
if( !Checkjson.test.phoneNumber( "", phones[ i ].trim() ) ) {
return false
}
}
};
return true;
};
// Checkjson.normalize take a correct data then reformat it to harmonise it
Checkjson.normalize = {};
Checkjson.normalize.phoneNumber = ( ctx, phone ) => {
phone = phone.trim()
.replace( /[- .]/g, '' );
if( Checkjson.test.phoneNumber( '', phone ) && phone.length == 10 && phone[ 0 ] == "0" ) {
phone = '+33 ' + phone.substring( 1 );
}
return phone;
}
Checkjson.normalize.upperCase = ( ctx, txt ) => txt.toUpperCase();
Checkjson.normalize.lowerCase = ( ctx, txt ) => txt.toLowerCase();
// fixe 10 position et complete par des 0 devant
Checkjson.normalize.zfill10 = ( ctx, num ) => {
let s = num + '';
while( s.length < 10 ) s = '0' + s;
return s;
};
/*let tt = "+33 1 02.03 04 05";
console.log(Checkjson.test.phoneNumber('', tt))
console.log(Checkjson.normalize.phoneNumber('', tt))
*/
Checkjson.evaluate = ( contexte, referential, data ) => {
/*
* contexte object {} with full info for evaluation
* file referential path to get object to apply
* data related to object
- return {validefor =[keyword of error] if empty no error,
clean data eventually reformated
updateDatabase}
*/
console.log( 'contexte', contexte );
console.log( 'referentiel', referential );
console.log( 'data', data );
const invalidefor = [];
const objectdef = {};
const listfield = referential.map( ch => {
objectdef[ ch.idfield ] = ch;
return ch.idfield;
} );
Object.keys( data )
.forEach( field => {
if( !listfield.includes( field ) ) {
// some data can be inside an object with no control at all
// they are used for process only
// i leave it in case it will become a non sens
// invalidefor.push('ERRFIELD unknown of referentials ' + field);
} else {
if( objectdef[ field ].check ) {
// check data with rule list in check
objectdef[ field ].Checkjson.forEach( ctrl => {
console.log( 'ctrl', ctrl );
contexte.currentfield = field;
if( !Checkjson.test[ ctrl ] ) {
invalidefor.push( 'ERR check function does not exist :' + ctrl + '___' + field )
} else {
if( !Checkjson.test[ ctrl ]( contexte, data[ field ] ) )
invalidefor.push( 'ERR' + ctrl + '___' + field );
}
} );
}
if( objectdef[ field ].nouserupdate ) {
// check if user can modify this information
console.log(
'evaluation :' + field + ' -- ' + objectdef[ field ].nouserupdate,
eval( objectdef[ field ].nouserupdate )
);
const evalright = eval( objectdef[ field ].nouserupdate );
objectdef[ field ].nouserupdate = evalright;
}
}
} );
console.log( {
invalidefor,
data
} );
return {
invalidefor,
data
};
};
if( typeof module !== 'undefined' ) module.exports = Checkjson;

File diff suppressed because one or more lines are too long

View File

@ -1,150 +0,0 @@
/*
After state.js / auth.js and all external js lib
Load
*/
var pwa = pwa || {};
pwa.main = pwa.main || {};
pwa.main.tpldata = pwa.main.tpldata || {};
pwa.main.tpl = pwa.main.tpl || {};
pwa.main.tpldata = pwa.main.tpldata || {};
pwa.main.ref = pwa.main.ref || {};
pwa.main.tpl.appsidebarmenu = 'static/components/appmesa/appsidebarmenu.mustache';
pwa.main.tpl.apptopbarmenu = 'static/components/appmesa/apptopbarmenu.mustache';
pwa.main.tpldata.sidebar = `static/components/appmesa/data_sidebar`;
pwa.main.tpldata.topbar = `static/components/appmesa/data_topbar`;
pwa.main.tpldata.topbarLogin = `static/components/appmesa/data_topbarLogin`;
pwa.main.init = () => {
const isempty = ( obj ) => {
return obj && Object.keys( obj )
.length === 0 && obj.constructor === Object
}
// Load public env tpl & tpldata
//Manage action depending of html file currently show
const currenthtml = location.pathname.split( '/' )
.at( -1 );
console.groupCollapsed( `pwa.main.init for ${currenthtml} html page` );
if( currenthtml.includes( 'app_' ) ) {
pwa.main.loadmenu()
}
// To manage if authenticated or not in a simple way
/*
if( pwa.state.data.login.isAuthenticated ) {
//authenticated
// identity inside pwa.state.login.user
}else{
//anonymous
// can check if the url is relevant with isAuthenticated
//route to app if exist data-routo into a signin
//pwa.auth.route( document.querySelector( '#signin button[data-routeto]' ).getAttribute( 'data-routeto' ) );
// add and load dynamicaly the gui.js plugin if user that request it has access
}
*/
console.groupEnd();
};
pwa.main.loadmenu = async () => {
console.log( 'pwa.main.loadmenu running' );
console.log( 'Status of pwa.state.data.login.isAuthenticated =', pwa.state.data.login.isAuthenticated );
let datasidebar, datatopbar;
/* Build datasidebar and datatopbar depending of list of module allowed by user in his ACCESSRIGHTS profil.
app[`${pwa.state.data.ctx.tribeid}:${pwa.state.data.ctx.website}`].js;
*/
//console.log( 'List of tpldata', pwa.main.tpldata )
//console.log( 'List of tpl', pwa.main.tpl )
console.log( `run pwa.state.loadfile with pwa.state.data.ctx.refreshstorage = ${pwa.state.data.ctx.refreshstorage} if true=> refresh anyway, if false refresh only if dest.name does not exist` );
await pwa.state.loadfile( pwa.main.tpl, 'tpl' );
await pwa.state.loadfile( pwa.main.tpldata, 'tpldata' );
datasidebar = pwa.state.data.tpldata.sidebar;
//any tpldata containing sidebar in pwa.state.data.tpldata is add to sbgroupmenu to be available
Object.keys( pwa.state.data.tpldata )
.filter( m => ( m != 'sidebar' && m.includes( 'sidebar' ) ) )
.some( k => {
datasidebar.sbgroupmenu.push( pwa.state.data.tpldata[ k ] )
} );
//merge les menu topbar
datatopbar = pwa.state.data.tpldata.topbar;
if( pwa.state.data.login.isAuthenticated ) {
// update user information if needed
datatopbar.name = pwa.state.data.login.user.LOGIN;
datatopbar.avatarimg = pwa.state.data.login.user.AVATARIMG;
delete pwa.state.data.tpldata.topbarLogin;
pwa.state.save();
}
datatopbar.menuprofil = [];
Object.keys( pwa.state.data.tpldata )
.filter( m => ( m != 'topbar' && m.includes( 'topbar' ) ) )
.some( k => {
datatopbar.menuprofil.push( pwa.state.data.tpldata[ k ] )
} );
if( pwa.state.data.tpl.appsidebarmenu ) {
document.querySelector( "#sidebar" )
.innerHTML = Mustache.render( pwa.state.data.tpl.appsidebarmenu, datasidebar )
document.querySelector( "#navbar" )
.innerHTML = Mustache.render( pwa.state.data.tpl.apptopbarmenu, datatopbar )
//active les icones svg de feather
feather.replace();
//active scroll presentation + sidebar animation
pwa.main.simplebar();
pwa.main.clickactive();
};
};
//////////////////////////////////////////////////////
// simplebar
//////////////////////////////////////////////////////
pwa.main.simplebar = () => {
const simpleBarElement = document.getElementsByClassName( "js-simplebar" )[ 0 ];
if( simpleBarElement ) {
/* Initialize simplebar */
new SimpleBar( document.getElementsByClassName( "js-simplebar" )[ 0 ] )
const sidebarElement = document.getElementsByClassName( "sidebar" )[ 0 ];
const sidebarToggleElement = document.getElementsByClassName( "sidebar-toggle" )[ 0 ];
sidebarToggleElement.addEventListener( "click", () => {
sidebarElement.classList.toggle( "collapsed" );
sidebarElement.addEventListener( "transitionend", () => {
window.dispatchEvent( new Event( "resize" ) );
} );
} );
}
}
/////////////////////////////////////////////////////////
// manage click effect
////////////////////////////////////////////////////////
pwa.main.clickactive = () => {
const cleanactive = () => {
const el = document.querySelectorAll( '.sidebar-item' )
for( var i = 0; i < el.length; i++ ) {
//console.log( 'clean', el[ i ].classList )
el[ i ].classList.remove( 'active' );
}
}
document.addEventListener( "click", ( e ) => {
console.log( 'click', e );
if( e.target.classList.contains( 'sidebar-link' ) ) {
cleanactive();
e.target.closest( '.sidebar-item' )
.classList.add( 'active' );
// remonte au menu au dessus si existe
e.target.closest( '.sidebar-item' )
.closest( '.sidebar-item' )
.classList.add( 'active' );
}
} );
// If enter run the research
document.getElementById( 'globalsearch' )
.addEventListener( 'keypress', ( e ) => {
if( e.keyCode == 13 ) {
pwa.search.req( 'globalsearch' );
e.preventDefault();
}
} )
};

View File

@ -1,28 +0,0 @@
"use strict";
var pwa = pwa || {};
/*
Manage notification
Get notification after tomenu was load
from /components/notification
____________________
*/
//--##
pwa.notification = {};
pwa.notification.update = () => {
console.log( 'get notification update for a user' );
axios.get( `https://${pwa.state.data.ctx.urlbackoffice}/notifications/user`, { headers: pwa.state.data.headers } )
.then( rep => {
console.log( "list des notifs", rep.data.payload.data )
rep.data.payload.data.number = rep.data.payload.data.notifs.length;
document.getElementById( "topbarmenuright" )
.innerHTML = Mustache.render( pwa.state.data.tpl.notiflist, rep.data.payload.data ) + document.getElementById( "topbarmenuright" )
.innerHTML;
} )
.catch( err => {
console.log( `Err pwa.notification.update data for user into header ${pwa.state.data.headers}`, err );
} );
};

File diff suppressed because one or more lines are too long

View File

@ -1,261 +0,0 @@
"use strict";
var pwa = pwa || {};
/*
FROM ndda/plugins/maildigitcreator/appjs/state.js
Manage state of the webapp
author: Phil Colzy - yzlocp@gmail.com
____________________________
pwa.state.save(): save in localstorage pwa.state.data avec le Nom du projet
____________________________
pwa.state.update(): update localstorage data from referential version
____________________________
pwa.state.ready(callback): await DOM loaded before running the callback
____________________________
pwa.state.refresh(): check if newversion of webapp to refresh page for dev purpose (do not use to refresh data)
____________________________
pwa.state.route(); check url and reroute it to function(urlparameter) or hide show part into a onepage website.
____________________________
pwa.state.loadfile({key:url},'dest') store in pwa.state.data.dest.key= file from url await all key to store result
___________________________
pwa.state.confdev() if ENV is dev then change urlbase for axios to looking for relevant file and refresh at a frequency pwa.state.refresh()
*/
//--##
pwa.state = {};
pwa.state.refresh = () => {
//console.warn(`Lance le refresh de${pwa.state.env.page}`)
//console.warn( 'ggg', pwa.state.data.ctx.urlbase )
const currenthtml = location.pathname.split( '/' )
.at( -1 )
.replace( '.html', '.json' );
//console.log( currenthtml )
axios.get( ` ${pwa.state.data.ctx.urlbase}/static/lastchange/${currenthtml}` )
.then(
data => {
//console.log( data.data.time, pwa.state.data.ctx.version )
if( data.data.time > pwa.state.data.ctx.version ) {
//console.log( "reload la page pour cause de lastchange detecté" );
pwa.state.data.ctx.version = data.data.time;
pwa.state.data.ctx.refreshstorage = true;
pwa.state.save();
location.reload();
} else {
//console.log( 'nothing change' )
}
},
error => {
console.log( error );
}
);
};
pwa.state.ready = callback => {
// Equivalent of jquery Document.ready()
// in case the document is already rendered
if( document.readyState != "loading" ) callback();
// modern browsers
else if( document.addEventListener )
document.addEventListener( "DOMContentLoaded", callback );
// IE <= 8
else
document.attachEvent( "onreadystatechange", function () {
if( document.readyState == "complete" ) callback();
} );
};
pwa.state.route = async () => {
/* Allow to create dynamic content
?action=pwa object&id=&hh& => pwa.action("?action=pwa object&id=&hh&")
ex: ?action=test.toto&id=1&t=123
Each function that can be called have to start with
if (e[1]=="?"){
const urlpar = new URLSearchParams( loc.search );
Then set param with urlpar.get('variable name')
}
OR ?pagemd=name used into .html (div)
Then it hide all <div class="pagemd" and show the one with <div id="page"+name
*/
console.groupCollapsed( `pwa.state.route with window.location` );
console.log( 'List of pwa available ', Object.keys( pwa ) );
if( !pwa.auth ) {
console.log( 'Warning, no auth.js, not a pb if no authentification need, if not check js order to be sur auth.js load before state.js' )
} else {
// check if still authenticated
if( pwa.state.data.login.isAuthenticated ) {
pwa.state.data.login.isAuthenticated = await pwa.auth.isAuthenticate();
}
//check if need authentification to show this page
if( pwa.state.data.ctx.pageneedauthentification && !pwa.state.data.login.isAuthenticated ) {
console.log( 'reload page cause not auth and page require an auth' )
window.location = `${pwa.state.data.ctx.pageredirectforauthentification}_${pwa.state.data.ctx.lang}.html`;
}
}
const loc = window.location;
if( loc.search ) {
console.log( Object.keys( pwa ) )
const urlpar = new URLSearchParams( loc.search );
if( urlpar.get( 'action' ) ) {
const act = 'pwa.' + urlpar.get( 'action' ) + '("' + loc.search + '")';
try {
eval( act );
console.log( 'Specific action request to pwa.' + act )
} catch ( err ) {
console.log( err )
console.error( `You request ${act}, this action does not exist ` );
alert( `Sorry but you have no access to ${act}, ask your admin` );
}
}
let pgid = "pageindex"
if( urlpar.get( 'pagemd' ) ) {
pgid = "page" + urlpar.get( 'pagemd' )
}
//route to page content
Array.from( document.getElementsByClassName( "pagemd" ) )
.forEach( e => {
console.log( "detect pagemd", e.getAttribute( 'data-url' ) );
e.classList.add( "d-none" );
} );
if( document.getElementById( pgid ) ) {
document.getElementById( pgid )
.classList.remove( 'd-none' );
}
}
console.groupEnd();
// If pwa.main exist then start pwa.main.init();
if( pwa.main ) pwa.main.init();
}
pwa.state.loadfile = async ( list, dest ) => {
// load external file if flag pwa.state.data.ctx.refreshstorage is true from pwa.state.refresh();
//from list = {name:url} request are done with ctx.urlbase/url and store in localstorage pwa.state.data[dest][name]=data
// if dest=='js' then it eval the js and store origin in pwa.state.data.js={name:url}
//For at true refreshstorage if destination pwa.state.dest does not exist
//console.log( 'list', list )
//console.log( 'pwa.state.data.ctx.refreshstorage', pwa.state.data.ctx.refreshstorage )
if( pwa.state.data.ctx.refreshstorage || !pwa.state.data[ dest ] || Object.keys( pwa.state.data[ dest ] )
.length == 0 ) {
if( !pwa.state.data[ dest ] ) pwa.state.data[ dest ] = {};
try {
let reqname = [];
let reqload = [];
for( const [ k, v ] of Object.entries( list ) ) {
if( !pwa.state.data[ dest ][ k ] || pwa.state.data.ctx.refreshstorage ) {
// if still not exist or refresstorage is set to true then add to load
//@TODO check it works well on production
reqname.push( k );
reqload.push( v );
}
};
//console.log( pwa.state.data.ctx.urlbase, reqload )
let resload = await Promise.all( reqload.map( r => {
if( dest == 'tpldata' ) r = `${r}_${pwa.state.data.ctx.lang}.json`;
return axios.get( `${pwa.state.data.ctx.urlbase}/${r}`, { headers: pwa.state.data.headers } )
} ) );
resload.forEach( ( d, i ) => {
pwa.state.data[ dest ][ reqname[ i ] ] = d.data;
pwa.state.save();
} )
} catch ( err ) {
console.error( 'FATAL ERROR check that list exist remove if not', list, err.message )
}
}
};
pwa.state.save = function () {
localStorage.setItem( pwa.state.data.ctx.website, JSON.stringify( pwa.state.data ) );
};
pwa.state.update = async function () {
const domhtml = document.querySelector( "html" );
const ctx = {
tribeid: domhtml.getAttribute( 'data-tribeid' ),
website: domhtml.getAttribute( "data-website" ),
nametpl: domhtml.getAttribute( "data-nametpl" ),
pagename: domhtml.getAttribute( "data-pagename" ),
urlbackoffice: domhtml.getAttribute( "data-urlbackoffice" ),
pageneedauthentification: true,
pageredirectforauthentification: "",
lang: domhtml.getAttribute( "lang" ),
env: domhtml.getAttribute( "data-env" ),
version: domhtml.getAttribute( "data-version" ),
refreshstorage: false
}
if( !domhtml.getAttribute( 'data-pageneedauthentification' ) || domhtml.getAttribute( 'data-pageneedauthentification' ) == 'false' ) {
ctx.pageneedauthentification = false;
}
if( domhtml.getAttribute( 'data-pageforauthentification' ) ) {
ctx.pageforauthentification = domhtml.getAttribute( 'data-pageforauthentification' );
}
console.groupCollapsed( `update pwa.state with html attribut or from localstorage into ${ctx.website}` );
console.log( 'html context:', ctx );
if( localStorage.getItem( ctx.website ) ) {
pwa.state.data = JSON.parse( localStorage.getItem( ctx.website ) );
//alert( 'recupere pwa.state.data xpaganid:' + pwa.state.data.headers.xpaganid )
}
if( !( pwa.state.data && pwa.state.data.ctx.tribeid == ctx.tribeid && pwa.state.data.ctx.website == ctx.website ) ) {
console.log( " reinitialise localstorage cause work on a different project or first access" );
delete pwa.state.data;
localStorage.removeItem( ctx.website )
}
/*
if( pwa.state.data && statejson.data.app.version && ( parseInt( pwa.state.data.app.version ) < parseInt( statejson.data.app.version ) ) ) {
// le numero de version en mémoire est < au numero disponible sur le serveur
// force un logout pour reinitialiser les menus
delete pwa.state.data;
localStorage.removeItem( pwa.PROJET )
}
*/
if( !pwa.state.data ) {
// No localstorage available et one by default
pwa.state.data = {
ctx,
login: {
isAuthenticated: false,
user: {},
rememberMe: {}
},
headers: {
'xauth': '1',
'xpaganid': '1',
'xtribe': ctx.tribeid,
'xlang': ctx.lang,
'xworkon': ctx.tribeid,
'xapp': `${ctx.tribeid}:${ctx.website}`
}
}
console.log( 'load new state.data', pwa.state.data )
}
// Check if external component need to be load
const app = `${pwa.state.data.ctx.tribeid}:${pwa.state.data.ctx.website}`;
if( pwa.state.data.login.isAuthenticated &&
pwa.state.data.login.user.ACCESSRIGHTS.app[ app ] &&
pwa.state.data.login.user.ACCESSRIGHTS.app[ app ].js
) {
console.log( 'tttt', pwa.state.data.login.isAuthenticated, pwa.state.data.login.user.ACCESSRIGHTS.app[ app ].js )
pwa.state.data.login.user.ACCESSRIGHTS.app[ app ].js.some( ( u ) => {
console.log( `load from user ACCESSRIGHTS app[${pwa.state.data.ctx.tribeid}:${pwa.state.data.ctx.website}].js : ${u}` )
const script = document.createElement( 'script' );
script.src = u;
script.async = false;
document.body.appendChild( script );
} );
}
//Check dev to set parameter to simplify dev app
//check in confdev version and set pwa.state.data.ctx.refreshstorage at true if new version
pwa.state.confdev();
console.groupEnd();
pwa.state.route();
pwa.state.save();
};
pwa.state.confdev = () => {
if( pwa.state.data.ctx.env == 'dev' ) {
pwa.state.data.ctx.urlbase = `/space/${pwa.state.data.ctx.tribeid}/${pwa.state.data.ctx.website}/dist`;
// check each 3 sec if new version to reload
setInterval( "pwa.state.refresh()", 3000 );
} else {
//pwa.state.axios = axios.create();
pwa.state.data.ctx.urlbase = "/";
// check and refresh if new version only one time
pwa.state.refresh();
}
}
// Refresh browser state if exist else get pwa.state defaults
pwa.state.ready( pwa.state.update );

View File

@ -1 +0,0 @@
{"name":"apxtrib Need-Data","short_name":"apxtrib","start_url":"app_index_fr.html","background_color":"purple","description":"Webapp to manage an apxtrib server.","display":"fullscreen","icons":[{"src":"static/img/icons/iconX74x74.png","sizes":"74x74","type":"image/png"}]}

View File

@ -1,2 +0,0 @@
/*Automaticaly generated do not change*/
@import "../../src/scss/app.scss";

View File

@ -1,34 +0,0 @@
pwa = pwa || {};
pwa.main = pwa.main || {};
pwa.main.tpldata = pwa.main.tpldata || {};
pwa.main.tpl = pwa.main.tpl || {};
//menu
pwa.main.tpldata.sidebarAdminapxtrib = `static/components/adminapxtrib/sidebaradminapxtrib`;
// Custom data in user lang
//tremplate to store
pwa.main.tpl.adminapxtrib = 'static/components/adminapxtrib/adminapxtrib.mustache';
pwa.main.tpl.adminapxtribsysinfo = 'static/components/adminapxtrib/adminapxtribsysinfo.mustache';
pwa.main.tpl.adminapxtribactivity = 'static/components/adminapxtrib/adminapxtribactivity.mustache';
pwa.adminapxtrib = {};
pwa.adminapxtrib.init = () => {
// Run back stuff to update data
}
pwa.adminapxtrib.sysinfoview = () => {
const datasysinfo = {}; //request to get info and push them in template
document.getElementById( 'maincontent' )
.innerHTML = Mustache.render( pwa.state.data.tpl.adminapxtribsysinfo, datasysinfo );
}
pwa.adminapxtrib.activityview = () => {
const dataactivity = {}; //request to get info and push them in template
document.getElementById( 'maincontent' )
.innerHTML = Mustache.render( pwa.state.data.tpl.adminapxtribactivity, dataactivity );
}
pwa.adminapxtrib.tribeidview = () => {
const datatribeid = {}; //request to get info and push them in template
document.getElementById( 'maincontent' )
.innerHTML = Mustache.render( pwa.state.data.tpl.adminapxtrib, datatribeid );
}

View File

@ -1,234 +0,0 @@
<div class="mb-3">
<h1 class="h3 d-inline align-middle">tribeids</h1><a class="badge bg-primary ms-2" href="" target="_blank">120 <i class="fas fa-fw fa-external-link-alt"></i></a>
</div>
<div class="row">
<div class="col-xl-8">
<div class="card">
<div class="card-header pb-0">
<div class="card-actions float-end">
<div class="dropdown position-relative">
<a href="#" data-bs-toggle="dropdown" data-bs-display="static" aria-expanded="false" class="">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-more-horizontal align-middle"><circle cx="12" cy="12" r="1"></circle><circle cx="19" cy="12" r="1"></circle><circle cx="5" cy="12" r="1"></circle></svg>
</a>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</div>
</div>
<h5 class="card-title mb-0">Tribes</h5>
</div>
<div class="card-body">
<table class="table table-striped" style="width:100%">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Company</th>
<th>Email</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="img/avatars/avatar.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Garrett Winters</td>
<td>Good Guys</td>
<td>garrett@winters.com</td>
<td><span class="badge bg-success">Active</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Ashton Cox</td>
<td>Levitz Furniture</td>
<td>ashton@cox.com</td>
<td><span class="badge bg-success">Active</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Sonya Frost</td>
<td>Child World</td>
<td>sonya@frost.com</td>
<td><span class="badge bg-danger">Deleted</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Jena Gaines</td>
<td>Helping Hand</td>
<td>jena@gaines.com</td>
<td><span class="badge bg-warning">Inactive</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-2.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Charde Marshall</td>
<td>Price Savers</td>
<td>charde@marshall.com</td>
<td><span class="badge bg-success">Active</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-2.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Haley Kennedy</td>
<td>Helping Hand</td>
<td>haley@kennedy.com</td>
<td><span class="badge bg-danger">Deleted</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-2.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Tatyana Fitzpatrick</td>
<td>Good Guys</td>
<td>tatyana@fitzpatrick.com</td>
<td><span class="badge bg-success">Active</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-3.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Michael Silva</td>
<td>Red Robin Stores</td>
<td>michael@silva.com</td>
<td><span class="badge bg-success">Active</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-3.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Angelica Ramos</td>
<td>The Wiz</td>
<td>angelica@ramos.com</td>
<td><span class="badge bg-success">Active</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-4.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Jennifer Chang</td>
<td>Helping Hand</td>
<td>jennifer@chang.com</td>
<td><span class="badge bg-warning">Inactive</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-4.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Brenden Wagner</td>
<td>The Wiz</td>
<td>brenden@wagner.com</td>
<td><span class="badge bg-warning">Inactive</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-4.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Fiona Green</td>
<td>The Sample</td>
<td>fiona@green.com</td>
<td><span class="badge bg-warning">Inactive</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-5.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Prescott Bartlett</td>
<td>The Sample</td>
<td>prescott@bartlett.com</td>
<td><span class="badge bg-success">Active</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-5.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Gavin Cortez</td>
<td>Red Robin Stores</td>
<td>gavin@cortez.com</td>
<td><span class="badge bg-success">Active</span></td>
</tr>
<tr>
<td><img src="img/avatars/avatar-5.jpg" width="32" height="32" class="rounded-circle my-n1" alt="Avatar"></td>
<td>Howard Hatfield</td>
<td>Price Savers</td>
<td>howard@hatfield.com</td>
<td><span class="badge bg-warning">Inactive</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-xl-4">
<div class="card">
<div class="card-header">
<div class="card-actions float-end">
<div class="dropdown position-relative">
<a href="#" data-bs-toggle="dropdown" data-bs-display="static">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-more-horizontal align-middle"><circle cx="12" cy="12" r="1"></circle><circle cx="19" cy="12" r="1"></circle><circle cx="5" cy="12" r="1"></circle></svg>
</a>
<div class="dropdown-menu dropdown-menu-end">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</div>
</div>
<h5 class="card-title mb-0">Angelica Ramos</h5>
</div>
<div class="card-body">
<div class="row g-0">
<div class="col-sm-3 col-xl-12 col-xxl-3 text-center">
<img src="img/avatars/avatar-3.jpg" width="64" height="64" class="rounded-circle mt-2" alt="Angelica Ramos">
</div>
<div class="col-sm-9 col-xl-12 col-xxl-9">
<strong>About me</strong>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua.</p>
</div>
</div>
<table class="table table-sm mt-2 mb-4">
<tbody>
<tr>
<th>Name</th>
<td>Angelica Ramos</td>
</tr>
<tr>
<th>Company</th>
<td>The Wiz</td>
</tr>
<tr>
<th>Email</th>
<td>angelica@ramos.com</td>
</tr>
<tr>
<th>Phone</th>
<td>+1234123123123</td>
</tr>
<tr>
<th>Status</th>
<td><span class="badge bg-success">Active</span></td>
</tr>
</tbody>
</table>
<strong>Activity</strong>
<ul class="timeline mt-2 mb-0">
<li class="timeline-item">
<strong>Signed out</strong>
<span class="float-end text-muted text-sm">30m ago</span>
<p>Nam pretium turpis et arcu. Duis arcu tortor, suscipit...</p>
</li>
<li class="timeline-item">
<strong>Created invoice #1204</strong>
<span class="float-end text-muted text-sm">2h ago</span>
<p>Sed aliquam ultrices mauris. Integer ante arcu...</p>
</li>
<li class="timeline-item">
<strong>Discarded invoice #1147</strong>
<span class="float-end text-muted text-sm">3h ago</span>
<p>Nam pretium turpis et arcu. Duis arcu tortor, suscipit...</p>
</li>
<li class="timeline-item">
<strong>Signed in</strong>
<span class="float-end text-muted text-sm">3h ago</span>
<p>Curabitur ligula sapien, tincidunt non, euismod vitae...</p>
</li>
<li class="timeline-item">
<strong>Signed up</strong>
<span class="float-end text-muted text-sm">2d ago</span>
<p>Sed aliquam ultrices mauris. Integer ante arcu...</p>
</li>
</ul>
</div>
</div>
</div>
</div>

View File

@ -1,22 +0,0 @@
{
"groupheader": "Admin apxtrib",
"sbssgroupmenu": [{
"name": "Activité",
"icon": "sliders",
"actionclick": "pwa.adminapxtrib.init()",
"iditemmenus": "adminxpress",
"itemmenus": [{
"name": "Info activités",
"actionclick": "pwa.adminapxtrib.activityview()"
},
{
"name": "Admin des tribeid",
"actionclick": "pwa.adminapxtrib.tribeidview()"
}
]
}, {
"name": "System Info",
"icon": "sliders",
"actionclick": "pwa.adminapxtrib.sysinfoview()"
}]
}

View File

@ -1,22 +0,0 @@
{
"groupheader": "Admin apxtrib",
"sbssgroupmenu": [{
"name": "Tribes",
"icon": "sliders",
"actionclick": "pwa.tribeids.init()",
"iditemmenus": "admintribeid",
"itemmenus": [{
"name": "Suivi des tribeid",
"actionclick": "pwa.tribeids.tribeidactivity()"
},
{
"name": "Admin des tribeid",
"actionclick": "pwa.tribeids.settings()"
}
]
}, {
"name": "Suivi technique",
"icon": "sliders",
"actionclick": "pwa.tribeids.suivi()"
}]
}

Some files were not shown because too many files have changed in this diff Show More