update auth openpgp.js

This commit is contained in:
2023-05-12 07:59:32 +02:00
parent dc11e8235e
commit a78bd8404a
85 changed files with 47890 additions and 1042 deletions

View File

@@ -1,82 +1,95 @@
const conf = require( '../../nationchains/tribes/conf.json' );
const conf = require("../../nationchains/tribes/conf.json");
const checkHeaders = ( req, res, next ) => {
/**
* @apiDefine apxHeader
* @apiGroup Middleware
* @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
* For performance, tokens are store globaly in req.app.locals.tokens={xpaganid:xauth}
* if xlang is not in conf.languagesAvailable
*
* @apiHeader {string} xjwt Pagans unique jwt token store in local town Pagans data or "noauth"
* @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} xtribe Tribes id where pseudo want to act
* @apiHeader {string} xapp Name of www/xapp folder that host app that send the request
* /tribeid/person/xpseudo.json have accessright on this app store in /tribe/tribeid/www/xapp
*
* @apiError missingexposedHeaders it miss an exposedHeaders
*
* @apiErrorExample {json} Error-Response:
* HTTP/1/1 404 Not Found
* {
* status:400,
* ref:"middleware"
* msg:"missingheaders",
* data: ["xpseudo","xjwt"]
* }
*
* @apiHeaderExample {json} Header-Exemple:
* {
* xtribe:"apache",
* xalias:"toto",
* xhash:"",
* xlang:"en",
* xapp:"popular"
* }
*/
req.session = {};
const header = {};
if (!req.header('xlang') && req.header('Content-Language')) req.params.xlang=req.header('Content-Language');
let missingheader = [];
console.log('req.headers',req.headers)
for( const h of conf.api.exposedHeaders ) {
//console.log( h, req.header( h ) )
if( req.params[ h ] ) {
header[ h ] = req.params[ h ]
} else if( req.header( h ) ) {
header[ h ] = req.header( h )
} else {
missingheader.push(h);
}
};
//console.log( 'header', header )
// store in session the header information
req.session.header = header;
// Each header have to be declared
if( missingheader != "" ) {
// bad request
return res.status( 400 )
.json( {
ref:"headers",
msg: "missingheader",
data: missingheader
} );
};
//console.log( req.app.locals.tribeids )
if( !req.app.locals.tribeids.includes( header.xtribe ) ) {
return res.status( 400 )
.json( {
ref:"headers",
msg: 'tribeiddoesnotexist',
moreinfo: header.xtribe
} );
}
if( !conf.api.languages.includes( header.xlang ) ) {
console.log('warning language requested does not exist force to en glish')
header.xlang="en";
}
next();
const checkHeaders = (req, res, next) => {
/**
* @apiDefine apxHeader
* @apiGroup Middleware
* @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
* For performance, tokens are store globaly in req.app.locals.tokens={xpaganid:xauth}
* if xlang is not in conf.languagesAvailable
*
* @apiHeader {string} xjwt Pagans unique jwt token store in local town Pagans data or "noauth"
* @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} xtribe Tribes id where pseudo want to act
* @apiHeader {string} xapp Name of www/xapp folder that host app that send the request
* /tribeid/person/xpseudo.json have accessright on this app store in /tribe/tribeid/www/xapp
*
* @apiError missingexposedHeaders it miss an exposedHeaders
*
* @apiErrorExample {json} Error-Response:
* HTTP/1/1 400 Not Found
* {
* status:400,
* ref:"headers"
* msg:"missingheaders",
* data: ["headermissing1"]
* }
*@apiErrorExample {json} Error-Response:
* HTTP/1/1 404 Not Found
* {
* status:404,
* ref:"headers"
* msg:"tribeiddoesnotexist",
* data: {xalias}
* }
*
* @apiHeaderExample {json} Header-Exemple:
* {
* xtribe:"apache",
* xalias:"toto",
* xhash:"",
* xdays:"123"
* xlang:"en",
* xapp:"popular"
* }
*/
req.session = {};
const header = {};
if (!req.header("xlang") && req.header("Content-Language"))
req.params.xlang = req.header("Content-Language");
let missingheader = [];
console.log("req.headers", req.headers);
for (const h of conf.api.exposedHeaders) {
//console.log( h, req.header( h ) )
if (req.params[h]) {
header[h] = req.params[h];
} else if (req.header(h)) {
header[h] = req.header(h);
} else {
missingheader.push(h);
}
}
//console.log( 'header', header )
// store in session the header information
req.session.header = header;
// Each header have to be declared
if (missingheader != "") {
// bad request
return res.status(400).json({
ref: "headers",
msg: "missingheader",
data: missingheader,
});
}
//console.log( req.app.locals.tribeids )
// xtribe == "town" is used during the setup process
if (
!(
header.xtribe == "town" || req.app.locals.tribeids.includes(header.xtribe)
)
) {
return res.status(404).json({
ref: "headers",
msg: "tribeiddoesnotexist",
data: { xtribe: header.xtribe },
});
}
if (!conf.api.languages.includes(header.xlang)) {
console.log("warning language requested does not exist force to english");
header.xlang = "en";
}
next();
};
module.exports = checkHeaders;

View File

@@ -1,42 +1,69 @@
const fs = require( 'fs-extra' );
const glob = require( 'glob' );
const path = require( 'path' );
const fs = require("fs-extra");
const glob = require("glob");
const path = require("path");
const config = require( '../../nationchains/tribes/conf.json' );
const config = require("../../nationchains/tribes/conf.json");
const hasAccessrighton = ( object, action, ownby ) => {
/*
const hasAccessrighton = (object, action, ownby) => {
/*
@action (mandatory) : CRUDO
@object (mandatory)= name of a folder object in /tribeid space can be a tree for example objects/items
@ownby (option) = list des uuid propriétaire
return next() if all action exist in req.app.local.tokens[UUID].ACCESSRIGHTS.data[object]
OR if last action ="O" and uuid exist in ownBy
Careffull if you have many action CRO let O at the end this will force req.right at true if the owner try an action on this object
*/
return ( req, res, next ) => {
//console.log( 'err.stack hasAccessrights', err.statck )
//console.log( `test accessright on object:${object} for ${req.session.header.xworkon}:`, req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ] )
req.right = false;
if( req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ] && req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ][ object ] ) {
req.right = true;
[ ...action ].forEach( a => {
if( a == "O" && ownby && ownby.includes( req.session.header.xpaganid ) ) {
req.right = true;
} else {
req.right = req.right && req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ][ object ].includes( a )
}
} )
}
//console.log( 'Access data autorise? ', req.right )
if( !req.right ) {
return res.status( 403 )
.json( {
info:'forbiddenAccessright',
ref: 'headers',
moreinfo: {xpaganid:req.session.header.xpaganid,object:object, xworkon:req.session.header.xworkon, action:action}
} )
}
next();
}
}
need to check first a person exist with this alias in tribe
const person = fs.readJsonSync(
`${conf.dirname}/nationchains/tribes/${req.session.header.xtribe}/persons/${req.session.header.xalias}.json`
);
*/
return (req, res, next) => {
//console.log( 'err.stack hasAccessrights', err.statck )
//console.log( `test accessright on object:${object} for ${req.session.header.xworkon}:`, req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ] )
req.right = false;
if (
req.app.locals.tokens[req.session.header.xpaganid].ACCESSRIGHTS.data[
req.session.header.xworkon
] &&
req.app.locals.tokens[req.session.header.xpaganid].ACCESSRIGHTS.data[
req.session.header.xworkon
][object]
) {
req.right = true;
[...action].forEach((a) => {
if (a == "O" && ownby && ownby.includes(req.session.header.xpaganid)) {
req.right = true;
} else {
req.right =
req.right &&
req.app.locals.tokens[
req.session.header.xpaganid
].ACCESSRIGHTS.data[req.session.header.xworkon][object].includes(a);
}
});
}
//console.log( 'Access data autorise? ', req.right )
if (!req.right) {
return res.status(403).json({
info: "forbiddenAccessright",
ref: "headers",
moreinfo: {
xpaganid: req.session.header.xpaganid,
object: object,
xworkon: req.session.header.xworkon,
action: action,
},
});
}
next();
};
};
module.exports = hasAccessrighton;

View File

@@ -1,207 +1,106 @@
const jwt = require("jwt-simple");
const fs = require("fs-extra");
const moment = require("moment");
const dayjs = require("dayjs");
const glob = require("glob");
const openpgp = require("openpgp");
const conf = require("../../nationchains/tribes/conf.json");
const isAuthenticated = (req, res, next) => {
//once a day rm oldest tokens than 24hours
const isAuthenticated = async (req, res, next) => {
// once a day rm oldest tokens than 24hours tag job by adding tmp/tokensmenagedone{day}
const currentday = dayjs().date();
console.log("dayjs", currentday);
console.log(
"test si menagedone" + currentday,
!fs.existsSync(`${conf.dirname}/tmp/tokensmenagedone${currentday}`)
"if menagedone" + currentday,
!fs.existsSync(`${__base}tmp/tokensmenagedone${currentday}`)
);
if (!fs.existsSync(`${conf.dirname}/tmp/tokensmenagedone${currentday}`)) {
if (!fs.existsSync(`${__base}/tmp/tokens`))
fs.mkdirSync(`${__base}tmp/tokens`);
if (!fs.existsSync(`${__base}tmp/tokensmenagedone${currentday}`)) {
// clean oldest
const tsday = dayjs().date();
console.log("tsday", tsday);
glob.sync(`${conf.dirname}/tmp/tokensmenagedone*`).forEach((f) => {
const tsday = dayjs().valueOf(); // now in timestamp format
glob.sync(`${__base}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);
});
glob.sync(`${__base}tmp/tokens/*.json`).forEach((f) => {
if (tsday - parseInt(f.split("_")[1]) > 86400000) fs.remove(f);
});
}
//Check register in tmp/tokens/
console.log("isRegister?");
console.log("isAuthenticate?");
const resnotauth = {
ref: "headers",
msg: "notauthenticated",
data: {
xalias: req.session.header.xalias,
xtribe: req.session.header.xtribe,
xaliasexists: true,
},
};
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)
console.log(req.session.header);
if (req.session.header.xalias == "anonymous") {
console.log("alias anonymous means not auth");
return res.status(401).json(resnotauth);
}
const tmpfs = `${__base}tmp/tokens/${req.session.header.xalias}_${
req.session.header.xdays
}_${req.session.header.xhash.substring(20, 200)}`;
console.log(tmpfs);
if (!fs.existsSync(tmpfs)) {
// need to check detached sign
let publickey;
if (
fs.existsSync(
`${__base}nationchains/pagans/itm/${req.session.header.xalias}.json`
)
) {
const pagan = fs.readJsonSync(
`${__base}nationchains/pagans/itm/${req.session.header.xalias}.json`
);
publickey = pagan.publicKey;
} else {
resnotauth.data.xaliasexists = false;
if (req.body.publickey) {
publickey = req.body.publickey;
} else {
console.log("alias unknown");
return res.status(404).send(resnotauth);
}
}
console.log(publickey);
console.log(Buffer.from(req.session.header.xhash, "base64").toString());
const publicKey = await openpgp.readKey({ armoredKey: publickey });
const msg = await openpgp.createMessage({
text: `${req.session.header.xalias}_${req.session.header.xdays}`,
});
const signature = await openpgp.readSignature({
armoredSignature: Buffer.from(
req.session.header.xhash,
"base64"
).toString(),
});
console.log(msg);
console.log(signature);
console.log(publicKey);
const checkauth = await openpgp.verify({
message: msg,
signature: signature,
verificationKeys: publicKey,
});
console.log(checkauth);
console.log(checkauth.signatures[0].keyID);
//console.log(await checkauth.signatures[0].signature);
//console.log(await checkauth.signatures[0].verified);
const { check, keyID } = checkauth.signatures[0];
try {
await check; // raise an error if necessary
fs.outputFileSync(tmpfs, req.session.header.xhash, "utf8");
} catch (e) {
resnotauth.msg = "signaturefailed";
console.log("not auth fail sign");
return res.status(401).send(resnotauth);
}
}
console.log("Authenticated");
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

@@ -1,7 +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}}"
}
"missingheader": "Some header miss to have a valid request: {{#data}} {{.}} {{/data}}",
"tribeiddoesnotexist": "Header xtribe: {{data.xtribe}} does not exist in this town",
"authenticated": "Your alias{{{data.xalias}}} is authenticated",
"notauthenticated": "Your alias: {{data.xalias}} is not authenticated {{^data.aliasexists}} and this alias does not exist !{{/data.aliasexists}}",
"forbiddenAccessright": "Pagan {{data.xalias}} has not access right to act {{data.action}} onto object {{data.object}} for tribe {{mor.xworkon}}"
}

View File

@@ -0,0 +1,20 @@
const glob = require("glob");
const path = require("path");
const fs = require("fs-extra");
/**
* To manage any communication between Pagan
* mayor druid emailing/sms/paper from tribe register smtp, simcard, mail api to Person(s) / Pagan(s)
* volatile notification message from tribe activities to Pagans / person ()
*
*/
const Notifications = {};
Notifications.send = (data) => {
const ret = {};
console.log("TODO dev notification emailing");
return ret;
};
module.exports = Notifications;

View File

@@ -1,97 +1,125 @@
const glob = require("glob");
const path = require("path");
const dayjs = require("dayjs");
const fs = require("fs-extra");
const axios = require('axios');
const openpgp = require('openpgp');
const conf=require('../../nationchains/tribes/conf.json')
const axios = require("axios");
const openpgp = require("openpgp");
var conf = {};
if (fs.existsSync("../../nationchains/tribes/conf.json")) {
conf = require("../../nationchains/tribes/conf.json");
}
console.log(conf);
/**
* Pagan Management numeric Identity
*
*
*
* Pagan Management numeric Identity and Person (Person = Pagan Id + tribe)
*
*
*
*/
const Pagans= {}
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')
});
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}}
}
//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 (
Pagans.create = (alias, publicKey) => {
/**
* @param {string} alias a unique alias that identify an identity
* @param {string} publicKey a publicKey
* @return {object} { status: 200, data: { alias, publicKey } }
* xhash was checked by isauthenticated
* @todo use Odmdb to add a pagan
*/
let apxpagans = {};
if (fs.existsSync(`${__base}nationchains/pagans/idx/alias_all.json`)) {
apxpagans = fs.readJsonSync(
`${__base}nationchains/pagans/idx/alias_all.json`
);
}
apxpagans[alias] = { alias, publicKey };
fs.outputJsonSync(
`${__base}nationchains/pagans/idx/alias_all.json`,
apxpagans
);
fs.outputJsonSync(`${__base}nationchains/pagans/itm/${alias}.json`, {
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;
}
publicKey,
});
return { status: 200, data: { alias, publicKey } };
};
Pagans.personupdate = (alias, tribe, persondata) => {
//later use Odmdb ans schema person to manage this
/**
* @Param {string} alias pagan unique id
* @Param {string} tribe tribe id in this town
* @Param {object} persondata that respect /nationchains/schema/person.json + nationchains/tribe/tribeid/schema/personextented.json
* @return create or update a person /tribe/tribeid/person/alias.json
*/
let person = {
alias: alias,
dt_create: dayjs(),
accessrights: { profil: "user" },
};
module.exports=Pagans;
if (fs.existsSync(`${__base}tribes/${tribe}/person/itm/${alias}.json`)) {
person = fs.readJsonSync(
`${__base}tribes/${tribe}/person/itm/${alias}.json`
);
person.dt_update = dayjs();
}
Object.keys(persondata).forEach((d) => {
person[d] = persondata[d];
});
//const checkjson= Checkjson.schema.data = (fs.readJsonSync(`${__base}}nationchains/schema/person.json`, person, false)
// if checkjson.status==200 create /update with odmdb to update index data
// see odmdb that did all and return standard message
fs.outputJSONSync(
`${__base}tribes/${tribe}/person/itm/${alias}.json`,
person,
{
space: 2,
}
);
return {
status: 200,
ref: "Pagans",
msg: "successfullupdate",
data: { tribe: tribe },
};
};
Pagans.authenticatedetachedSignature = async (
alias,
pubK,
detachedSignature,
message
) => {
/**
* Check that a message was signed with a privateKey from a publicKey
* This is not necessary if isAuthenticated, but can be usefull to double check
* @TODO finish it and implement it also in /apxpagan.js for browser
* @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

@@ -4,6 +4,7 @@ const dnsSync = require("dns-sync");
const mustache = require("mustache");
const readlineSync = require("readline-sync");
const Wwws = require("../models/Wwws.js");
/**
* This Setup is run at the first installation
* This is not an exportable module
@@ -28,9 +29,9 @@ Setup.check = () => {
);
process.exit();
}
if (fs.existsSync("./nationchains/tribes/conf.json")) {
if (fs.existsSync("./nationchains/www/nginx_adminapx.conf")) {
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, check http://adminapx or remove ./nationchains/www/nginx_adminapx.conf to reset a sync with the last nationchains"
);
process.exit();
}
@@ -38,19 +39,51 @@ Setup.check = () => {
};
Setup.init = async () => {
/**
* create empty nationchains
* rsync all subfolder nationchains except the tribes/ and /www/nginx_adminapx.conf
*
* Then to send new version we fix a master production
*
*/
const initconf = fs.readJSONSync(
"./nationchains/www/adminapx/static/tpldata/initconf.json"
);
initconf.sudoerUser = process.env.USER;
initconf.dirname = path.resolve(`${__dirname}/../../`);
// To allow to serve the nation website until the end
initconf.nginx.include.push(
`${townconf.dirname}/nationchains/www/nginx_*.conf`
);
// To allow to serve tribes web site
initconf.nginx.include.push(
`${townconf.dirname}/nationchains/tribes/*/www/nginx_*.conf`
);
initconf.nginx.logs = `${townconf.dirname}/nationchains/logs/nginx`;
initconf.nginx.website = "adminapx";
initconf.nginx.fswww = "nationchains/"; //for a local tribe nationchains/tribes/tribeid
initconf.nginx.tribeid = "town";
initconf.nginx.pageindex = "index_en.html";
const nginxconf = Wwws.apxtribinstall(initconf);
if (nginxconf.status == 200) {
}
};
if (Setup.check()) Setup.init();
// After testing remove all stuff after this line
Setup.initold = async () => {
// Get standard conf and current data
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`
);
}
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(
@@ -95,7 +128,7 @@ Setup.init = async () => {
)
)
process.exit();
// saved and change nginx conf
if (!fs.existsSync("/etc/nginx/nginxconf.saved")) {
fs.moveSync("/etc/nginx/nginx.conf", "/etc/nginx/nginxconf.saved");
@@ -112,6 +145,16 @@ Setup.init = async () => {
mustache.render(tplnginxconf, townconf),
"utf8"
);
//proxyparam
const proxy_params = fs.readFileSync(
"./nationchains/www/adminapx/nginx/proxy_params.mustache",
"utf8"
);
fs.outputFileSync(
"/etc/nginx/proxy_params",
mustache.render(proxy_params, townconf),
"utf8"
);
const tplnginxwww = fs.readFileSync(
"./nationchains/www/adminapx/nginx/modelwebsite.conf.mustache",
"utf8"
@@ -124,8 +167,10 @@ Setup.init = async () => {
fs.outputJsonSync("./nationchains/tribes/conf.json", townconf, {
spaces: 2,
});
// Integrer cette partie du setup en inteactif.
// l'objectif du setup est de rendere accessible adminapx en local (IP local) ou production IP public
//CREATE A TOWN setup local voir utiliser towns.create
townconf.town = {
/* townconf.town = {
townId: townconf.townId,
nationId: townconf.nationId,
url: `http://${townconf.dns[0]}`,
@@ -133,9 +178,13 @@ Setup.init = async () => {
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});
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,
@@ -145,27 +194,47 @@ Setup.init = async () => {
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});
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/nginx`);
//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 ');
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
}*/
//fin de partie à integer dans l'interface graphique adminapx
//restart nginx
const { exec } = require("child_process");
exec(townconf.nginx.restart, (error, stdout, stderr) => {
if (error) {

118
api/models/Wwws.js Normal file
View File

@@ -0,0 +1,118 @@
const fs = require("fs-extra");
const path = require("path");
const dnsSync = require("dns-sync");
const mustache = require("mustache");
const readlineSync = require("readline-sync");
const conf = fs.existsSync("../../nationchains/tribes/conf.json")
? require("../../nationchains/tribes/conf.json")
: {};
const Wwws = {};
Wwws.apxtribinstall = (paramconf) => {
/**
* First install for a setup
*
*/
if (fs.existsSync("../../nationchains/www/nginx_adminapx.conf")) {
console.log("You already have a conf on this town");
process.exit();
}
//first install
const nginxconf = fs.readFileSync(
"../../nationchains/www/adminapx/static/tpl/nginx.conf.mustache",
"utf8"
);
const proxyparams = fs.readFileSync(
"../../nationchains/www/adminapx/static/tpl/nginxproxy_params.mustache",
"utf8"
);
// saved and change nginx conf
if (!fs.existsSync("/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"
);
}
fs.outputFileSync(
"/etc/nginx/nginx.conf",
mustache.render(nginxconf, paramconf),
"utf8"
);
fs.outputFileSync(
"/etc/nginx/proxy_params",
mustache.render(proxyparams, paramconf),
"utf8"
);
if (!fs.existsSync(paramconf.nginx.logs)) fs.mkdirSync(paramconf.nginx.logs);
paramconf.nginx.firstinstall = true;
fs.outputJsonSync("../../nationchains/tribes/conf.json", paramconf, {
space: 2,
});
return Www.create(paramconf.nginx);
};
Wwws.create = (paramnginx) => {
/**
* Create an nginx conf to make available https://adminapx on a local network
* paramconf nginx.fswww place where the www folder is /tribeId/
*/
const res = {
status: 200,
ref: "Www",
msg: "successfulwww",
data: { website: paramnginx.website },
};
const nginxwebsite = fs.readFileSync(
"../../nationchains/www/adminapx/static/tpl/nginxmodelwebsite.conf.mustache",
"utf8"
);
fs.outputFileSync(
`./${paramnginx.fswww}www/nginx_${paramnginx.website}.conf`,
mustache.render(nginxwebsite, paramnginx),
"utf8"
);
if (!fs.existsSync(`./${paramnginx.fswww}www/${paramnginx.website}`)) {
//See later how to generate specific template of webapp
fs.mkdirSync(`./${paramnginx.fswww}www/${paramnginx.website}`);
}
if (!fs.existsSync(`./${paramnginx.fswww}www/cdn`)) {
//See later how to generate specific template of webapp
fs.mkdirSync(`./${paramnginx.fswww}www/cdn`);
}
//restart nginx
const { exec } = require("child_process");
exec(paramnginx.restart, (error, stdout, stderr) => {
if (error) {
if (paramnginx.firstinstall) {
console.log("\x1b[42m", error, stdout, stderr, "x1b[0m");
}
//@todo supprimer la derniere config et relancer
res.status = 500;
res.msg = "nginxError";
res.data = { msg: `${error}<br>${stdout}<br>${stderr}` };
} else {
if (paramnginx.firstinstall) {
// the tribes/conf.json is saved in apxtribinstall
console.log(
`\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://adminapx\x1b[0m \x1b[42m \nto finish your town setup. Don't forget to set your localhost /etc/hosts by adding 127.0.0.1 adminapx or {LAN IP} adminapx . Check README's project to learn more. \x1b[0m\n\x1b[42m###########################################################################################\x1b[0m`
);
} else {
// add website to tribe conf
}
}
});
return res;
};
Wwws.setssl = () => {
// Run process to change nginx conf to get a ssl
};
Wwws.configlist = (tribeId) => {
//if accessright R return list of conf parameter {webapp:{conf parameter}}
const res = { status: 200, data: {} };
return res;
};
module.exports = Wwws;

View File

@@ -1,3 +1,5 @@
{
}
"successfullcreate": "Alias creation for {{alias}} successfull. {{#withemail}} An email was sent to {{email}}, if you do not receive it, please download your keys before living this page.{{/withemail}}",
"successfulluppdate": "Your alias as a Person is now update into {{tribe}}",
"tribedoesnotexist": "Your tribe {{tribe}} does not exist in this town"
}

View File

@@ -33,5 +33,9 @@ router.post( '/push', checkHeaders, ( req, res ) => {
res.send( { status: 200, payload: { moreinfo: fs.readFileSync( `${config.tribes}/${config.mayorId}/nationchains/nodes/${config.rootURL}`, 'utf-8' ) } } )
} )
router.get('/synchro',checkHeaders, isAuthenticated,(req,res)=>{
// run a sync from a list of electedtown to update nationchains folder
console.log('TODO')
})
module.exports = router;

View File

@@ -32,6 +32,7 @@ router.get(
* @apiSuccess (200) {object} data contains indexfile requested
*
*/
console.log("pzasse");
// indexname = objectname_key_value.json
let objectLocation = "../../nationchains/";
if (!conf.api.nationObjects.includes(req.params.objectname)) {
@@ -42,13 +43,11 @@ router.get(
if (fs.existsSync(indexpath)) {
res.status(200).json({ data: fs.readJsonSync(indexpath) });
} else {
res
.status(404)
.json({
ref: "Odmdb",
msg: "objectfiledoesnotexist",
data: { indexpath },
});
res.status(404).json({
ref: "Odmdb",
msg: "objectfiledoesnotexist",
data: { indexpath },
});
}
}
);
@@ -88,13 +87,11 @@ router.get(
if (fs.existsSync(objectpath)) {
res.status(200).json({ data: fs.readJsonSync(objectpath) });
} else {
res
.status(404)
.json({
ref: "Odmdb",
msg: "objectfiledoesnotexist",
data: { objectpath },
});
res.status(404).json({
ref: "Odmdb",
msg: "objectfiledoesnotexist",
data: { objectpath },
});
}
}
);

View File

@@ -1,12 +1,13 @@
const express = require( 'express' );
const path = require( 'path' );
const express = require("express");
const path = require("path");
// Classes
const Pagans = require( '../models/Pagans.js' );
const Pagans = require("../models/Pagans.js");
const Notifications = require("../models/Notifications.js");
// Middlewares
const checkHeaders = require( '../middlewares/checkHeaders' );
const isAuthenticated = require( '../middlewares/isAuthenticated' );
const hasAccessrighton = require( '../middlewares/hasAccessrighton' );
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const hasAccessrighton = require("../middlewares/hasAccessrighton");
const router = express.Router();
/*
models/Pagans.js
@@ -47,53 +48,107 @@ Owner means it can be Write/Delete if field OWNER contain the UUID that try to a
*/
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));
router.get("/isauth", checkHeaders, isAuthenticated, (req, res) => {
/**
* @api {get} /pagans/isregister
* @apiName Is register check xalias and xhash
* @apiGroup Pagans
*
* @apiUse apxHeader
*
* @apiError (400) {object} status missingheaders / xalias does not exist / signaturefailled
* @apiError (401) {object} alias anonymous (not authenticated)
* @apiError (404) {string} tribe does not exist
*
*
*
* @apiSuccess (200) {object} data contains indexfile requested
*
*/
res.send({
status: 200,
ref: "headers",
msg: "authenticated",
data: {
xalias: req.session.header.xalias,
},
});
});
router.post("/", checkHeaders, isAuthenticated, (req, res) => {
/**
* Create a pagan account from alias, publickey, if trusted recovery =>
* Create a person in xtribe/person/xalias.json with profil.auth={email,privatekey, passphrase}
* Middleware isAuthenticated check that:
* - xhash is well signed from private key linked to the publickey of alias
* - check that alias does not already exist (if yes then verifiedsigne would be false)
* Need to wait next block chain to be sure that alias is register in the blokchain
*/
console.log("pass ici", req.body);
const feedback = { alias: req.body.alias, publickey: req.body.publickey };
const newpagan = Pagans.create(req.body.alias, req.body.publickey);
if (newpagan.status == 200) {
if (req.body.email) {
feedback.withemail = true;
feedback.email = req.body.email;
feedback.privatekey = req.body.privatekey;
feedback.passphrase = req.body.passphrase;
Notifications.send({
type: "email",
from: "",
dest: [req.body.email],
tpl: "registeremail",
tribe: req.session.header.xtribe,
data: feedback,
});
}
if (req.body.trustedtribe) {
if (req.app.locals.tribeids.includes(req.body.trustedtribe)) {
delete feedback.withemail;
const persondata = { recovery: feedback };
res.send(
Pagans.personupdate(req.body.alias, req.body.trustedtribe, persondata)
);
} else {
res.send({
status: 404,
ref: "Pagans",
msg: "tribedoesnotexist",
data: { tribe: req.body.trustedtribe },
});
}
} else {
newpagan.data = feedback;
res.send(newpagan);
}
} else {
//error to create pagan
res.send(newpagan);
}
});
router.put("/person", checkHeaders, isAuthenticated, (req, res) => {
/**
* add/update a person = alias + tribe with specific accessright and specific schema link to tribe
* @todo add tribe/schema/person.json
*/
console.log(req.body);
res.send(
Pagans.personupdate(req.body.alias, req.session.header.xtribe, 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);
});
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 ) => {
if( req.session.header.xpseudo == "1" ) {
return res.status( 401 )
.send( { info: "not authenticate" } );
} else return res.status( 200 )
.send( { info: "well authenticated" } )
} )
router.post( '/login', checkHeaders, async ( req, res ) => {
// console.log('POST /users/login with: ', req.app.locals.header);
/*
/*router.get("/isauth", checkHeaders, isAuthenticated, (req, res) => {
if (req.session.header.xpseudo == "1") {
return res.status(401).send({ info: "not authenticate" });
} else return res.status(200).send({ info: "well authenticated" });
});*/
router.post("/login", checkHeaders, async (req, res) => {
// console.log('POST /users/login with: ', req.app.locals.header);
/*
Check un mot de passe pour un login pour obtenir un token d'authentification
valable 1 hour, 1 day
@header
@@ -104,21 +159,22 @@ router.post( '/login', checkHeaders, async ( req, res ) => {
utile le temps de reinitialisé son mot de passe.
@return
*/
console.log( 'login for ', req.body, "in", req.session.header )
const log = await Pagans.loginUser( req.session.header, req.body, true );
console.log( "log user login", log );
if( log.status == 200 ) {
// update req.app.locals.tokens for this uuid just after login success then next isAuth will be valid
req.app.locals.tokens[ log.data.user.UUID ] = { TOKEN: log.data.user.TOKEN, ACCESSRIGHTS: log.data.user.ACCESSRIGHTS }
console.log( req.app.locals )
}
return res.status( log.status )
.send( log.data );
} );
console.log("login for ", req.body, "in", req.session.header);
const log = await Pagans.loginUser(req.session.header, req.body, true);
console.log("log user login", log);
if (log.status == 200) {
// update req.app.locals.tokens for this uuid just after login success then next isAuth will be valid
req.app.locals.tokens[log.data.user.UUID] = {
TOKEN: log.data.user.TOKEN,
ACCESSRIGHTS: log.data.user.ACCESSRIGHTS,
};
console.log(req.app.locals);
}
return res.status(log.status).send(log.data);
});
router.get( '/getlinkwithoutpsw/:email', checkHeaders, async ( req, res ) => {
/*
router.get("/getlinkwithoutpsw/:email", checkHeaders, async (req, res) => {
/*
Permet pour un email existant de renvoyer un email avec un lien valable 1h
@email est le compte pour lequel on demande un accès
Réponse:
@@ -134,109 +190,161 @@ router.get( '/getlinkwithoutpsw/:email', checkHeaders, async ( req, res ) => {
}
}
*/
console.log( `GET /users/getlinkwithoutpsw for email: ${req.params.email} tribeid :${req.header('X-Client-Id')}` );
if( !req.params.email ) {
return res.status( 404 )
.send( {
info: [ 'emailmissing' ],
model: 'Pagans'
} );
} else {
try {
const getlink = await Pagans.getlinkwithoutpsw( req.params.email, req.session.header );
console.log( 'getlink', getlink )
//met à jour le token créer pour le uuid
req.app.locals.tokens[ getlink.data.info.xuuid ] = getlink.data.info.token;
// attention si on relance le serveur le token temporaire est perdu
return res.status( getlink.status )
.send( getlink.data );
} catch ( err ) {
console.log( err )
}
}
} );
router.post( '/register', checkHeaders, async ( req, res ) => {
console.log( `POST /users for ${req.session.header.xtribe}` );
if( req.session.header.xjwt == '123123' ) {
// Creation d'un utilisateur avec information de base aucun droit
// 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
console.log( 'req du post', req );
}
} );
router.get( '/info/:listindex', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'R' ), async ( req, res ) => {
console.log( `get users info on tribeid ${req.session.header.xworkon} for ${req.params.listindex} with accessright`, req.session.header.accessrights.data );
const result = await Pagans.getinfoPagans( req.session.header.xpresworkon, req.session.header.accessrights, req.params.listindex );
res.status( result.status )
.send( result.data );
} );
router.get( '/list/:filter/:field', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'R' ), async ( req, res ) => {
console.log( 'GET /users/list/filtre/champs list for ' + req.session.header.xworkon );
if(
[ 'admin', 'manager' ].includes( req.session.header.decodetoken[ 'apps' + req.session.header.xworkon + 'profil' ] ) ) {
try {
const userslist = await Pagans.getUserlist( req.session.header, req.params.filter, req.params.field );
console.log( 'userslist', userslist );
if( userslist.status == 200 ) {
return res.status( userslist.status )
.send( userslist.data );
}
} catch ( err ) {
console.log( err );
return res.status( 400 )
.send( { info: 'erreur' } );
}
} else {
res.status( 403 )
.send( {
info: [ 'forbiddenAccess' ],
model: 'Pagans'
} );
}
} );
router.get( '/uuid/:id', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'R' ), async ( req, res ) => {
console.log( `GET /users/uuid/${req.params.id}` );
//console.log('req.app.locals: ', req.app.locals);
//console.log('req.session', req.session);
const result = await Pagans.getUser( req.params.id, req.session.header.xworkon, req.session.header.accessrights );
res.status( result.status )
.send( result.data );
} );
router.put( '/chgpsw/:id', checkHeaders, isAuthenticated, async ( req, res ) => {
console.log( `PUT update /users/chgpsw/${req.params.id}` );
try {
const majpsw = await Pagans.updateUserpassword( req.params.id, req.session.header, req.body );
res.status( majpsw.status )
.send( majpsw.data );
} catch ( {
status,
data
} ) {
res.status( status )
.send( data );
}
} );
router.post( '/uuid', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'C' ), async ( req, res ) => {
console.log( 'POST /users create for ' + req.session.header.xworkon, req.body );
const usercreate = await Pagans.createUser( req.session.header, req.body );
return res.status( usercreate.status )
.send( usercreate.data );
} );
router.put( '/uuid/:id', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'U' ), async ( req, res ) => {
console.log( `PUT update /users/${req.params.id}` );
// console.log('req.app.locals: ', req.app.locals);
// console.log('req.session', req.session);
try {
const majUser = await Pagans.updateUser( req.params.id, req.session.header, req.body );
res.status( majUser.status )
.send( majUser.data );
} catch ( {
status,
data
} ) {
res.status( status )
.send( data );
}
} );
console.log(
`GET /users/getlinkwithoutpsw for email: ${
req.params.email
} tribeid :${req.header("X-Client-Id")}`
);
if (!req.params.email) {
return res.status(404).send({
info: ["emailmissing"],
model: "Pagans",
});
} else {
try {
const getlink = await Pagans.getlinkwithoutpsw(
req.params.email,
req.session.header
);
console.log("getlink", getlink);
//met à jour le token créer pour le uuid
req.app.locals.tokens[getlink.data.info.xuuid] = getlink.data.info.token;
// attention si on relance le serveur le token temporaire est perdu
return res.status(getlink.status).send(getlink.data);
} catch (err) {
console.log(err);
}
}
});
router.post("/register", checkHeaders, async (req, res) => {
console.log(`POST /users for ${req.session.header.xtribe}`);
if (req.session.header.xjwt == "123123") {
// Creation d'un utilisateur avec information de base aucun droit
// 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
console.log("req du post", req);
}
});
router.get(
"/info/:listindex",
checkHeaders,
isAuthenticated,
hasAccessrighton("users", "R"),
async (req, res) => {
console.log(
`get users info on tribeid ${req.session.header.xworkon} for ${req.params.listindex} with accessright`,
req.session.header.accessrights.data
);
const result = await Pagans.getinfoPagans(
req.session.header.xpresworkon,
req.session.header.accessrights,
req.params.listindex
);
res.status(result.status).send(result.data);
}
);
router.get(
"/list/:filter/:field",
checkHeaders,
isAuthenticated,
hasAccessrighton("users", "R"),
async (req, res) => {
console.log(
"GET /users/list/filtre/champs list for " + req.session.header.xworkon
);
if (
["admin", "manager"].includes(
req.session.header.decodetoken[
"apps" + req.session.header.xworkon + "profil"
]
)
) {
try {
const userslist = await Pagans.getUserlist(
req.session.header,
req.params.filter,
req.params.field
);
console.log("userslist", userslist);
if (userslist.status == 200) {
return res.status(userslist.status).send(userslist.data);
}
} catch (err) {
console.log(err);
return res.status(400).send({ info: "erreur" });
}
} else {
res.status(403).send({
info: ["forbiddenAccess"],
model: "Pagans",
});
}
}
);
router.get(
"/uuid/:id",
checkHeaders,
isAuthenticated,
hasAccessrighton("users", "R"),
async (req, res) => {
console.log(`GET /users/uuid/${req.params.id}`);
//console.log('req.app.locals: ', req.app.locals);
//console.log('req.session', req.session);
const result = await Pagans.getUser(
req.params.id,
req.session.header.xworkon,
req.session.header.accessrights
);
res.status(result.status).send(result.data);
}
);
router.put("/chgpsw/:id", checkHeaders, isAuthenticated, async (req, res) => {
console.log(`PUT update /users/chgpsw/${req.params.id}`);
try {
const majpsw = await Pagans.updateUserpassword(
req.params.id,
req.session.header,
req.body
);
res.status(majpsw.status).send(majpsw.data);
} catch ({ status, data }) {
res.status(status).send(data);
}
});
router.post(
"/uuid",
checkHeaders,
isAuthenticated,
hasAccessrighton("users", "C"),
async (req, res) => {
console.log(
"POST /users create for " + req.session.header.xworkon,
req.body
);
const usercreate = await Pagans.createUser(req.session.header, req.body);
return res.status(usercreate.status).send(usercreate.data);
}
);
router.put(
"/uuid/:id",
checkHeaders,
isAuthenticated,
hasAccessrighton("users", "U"),
async (req, res) => {
console.log(`PUT update /users/${req.params.id}`);
// console.log('req.app.locals: ', req.app.locals);
// console.log('req.session', req.session);
try {
const majUser = await Pagans.updateUser(
req.params.id,
req.session.header,
req.body
);
res.status(majUser.status).send(majUser.data);
} catch ({ status, data }) {
res.status(status).send(data);
}
}
);
module.exports = router;

45
api/routes/wwws.js Normal file
View File

@@ -0,0 +1,45 @@
const express = require("express");
const path = require("path");
// Classes
const Wwws = require("../models/Wwws.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const hasAccessrighton = require("../middlewares/hasAccessrighton");
const router = express.Router();
/**
* To manage an nginx conf
*
*/
router.get("/tribes/:tribeId", checkHeaders, isAuthenticated, (req, res) => {
/**
* @api {get} /www/tribes/:tribeId
* @apiName Get list of application Name
* @apiGroup Www
*
* @apiUse apxHeader
*
* @apiParam {String} tribeId Mandatory that have to exist in current town and
*
* @apiError (404) {string} status the folder 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 www's model: 'Www' } );render lg/objectmodel_lg.json
*
* @apiSuccess (200) {object} data contains liste of www conf of a tribe
*
*/
res.send(Www.configlist(req.params.tribeId));
});
router.post("/:webappname", checkHeaders, isAuthenticated, (req, res) => {
/**
* Create a space web /tribes/www/webappname
*
*
* */
res.send(Wwws.create(req.params.tribeId));
});
module.exports = router;