This commit is contained in:
philc 2023-06-28 13:28:37 +00:00
commit baf2f28070
32 changed files with 565 additions and 308 deletions

View File

@ -16,7 +16,7 @@
"title":"Creation date", "title":"Creation date",
"description":"Nation date of creation", "description":"Nation date of creation",
"type": "string", "type": "string",
"format":"datetime" "format":"date-time"
}, },
"contracts":{ "contracts":{
"title":"Social contract of the nation", "title":"Social contract of the nation",

View File

@ -17,20 +17,20 @@
}, },
"dt_create": { "dt_create": {
"type": "string", "type": "string",
"format": "datetime", "format": "date-time",
"default": "dayjs.now()" "default": "dayjs.now()"
}, },
"dt_update": { "dt_update": {
"type": "string", "type": "string",
"format": "datetime" "format": "date-time"
}, },
"dt_lastlogin": { "dt_lastlogin": {
"type": "string", "type": "string",
"format": "datetime" "format": "date-time"
}, },
"dt_close": { "dt_close": {
"type": "string", "type": "string",
"format": "datetime" "format": "date-time"
}, },
"recoveryauth": { "recoveryauth": {
"type": "object", "type": "object",

View File

@ -9,6 +9,7 @@
"mainlivinglocation":{"type":"object","$ref":"https://schema.org/PostalAddress"}, "mainlivinglocation":{"type":"object","$ref":"https://schema.org/PostalAddress"},
"secondlivinglocation":{"type":"object","$ref":"https://schema.org/PostalAddress"}, "secondlivinglocation":{"type":"object","$ref":"https://schema.org/PostalAddress"},
"thirdlivinglocation":{"type":"object","$ref":"https://schema.org/PostalAddress"}, "thirdlivinglocation":{"type":"object","$ref":"https://schema.org/PostalAddress"},
"fourthlivinglocation":{"type":"object","$ref":"https://schema.org/PostalAddress"},
"seekcriterias":{"type":"array","$ref":"schema/seekcriteria.json"}, "seekcriterias":{"type":"array","$ref":"schema/seekcriteria.json"},
"skills":{"type":"array","$ref":"schema/skills.json"}, "skills":{"type":"array","$ref":"schema/skills.json"},
"educations":{"type":"array","$ref":"schema/educations.json"}, "educations":{"type":"array","$ref":"schema/educations.json"},

View File

@ -21,10 +21,9 @@
"default": "active", "default": "active",
"type": "string", "type": "string",
"enum":["chain","unchain","tochain"] "enum":["chain","unchain","tochain"]
}
}, },
"dns": { "dns": {
"type": "array" "type": "string"
} }
}, },
"required": ["townId", "status", "nationId", "dns"], "required": ["townId", "status", "nationId", "dns"],
@ -34,4 +33,4 @@
{ "key": "nationId", "value": "townId" }, { "key": "nationId", "value": "townId" },
{ "key": "townId", "value": [] } { "key": "townId", "value": [] }
] ]
} }

View File

@ -17,10 +17,9 @@
"type": "string", "type": "string",
"$ref": "nationchains/nations/idx/nations_uuid_uuid.json" "$ref": "nationchains/nations/idx/nations_uuid_uuid.json"
}, },
"status": { "druidId": {
"default": "unchain",
"type": "string", "type": "string",
"enum": ["chain","tochain","unchain"] "$ref": "nationchains/pagans/idx/alias_all.json"
}, },
"dns": { "dns": {
"type": "array", "type": "array",

View File

@ -9,7 +9,7 @@ root {{{dirapi}}}/;
location ~* /nationchains/schema/ { location ~* /nationchains/schema/ {
#outside of nationchains for git purpose #outside of nationchains for git purpose
rewrite /nationchains/schema/(.*$) /$1 break; rewrite /nationchains/schema/(.*$) /$1 break;
root {{{dirapi}}}/adminapi/www/adminapx/schema/; root {{{dirapi}}}/adminapi/schema/;
} }
# /plugins/pluginame/components/xxx?plugin=pluginname&pluginkey=key # /plugins/pluginame/components/xxx?plugin=pluginname&pluginkey=key
# acess if exist pluginkey # acess if exist pluginkey

View File

@ -9,6 +9,8 @@
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- fontawesome icon cdn --> <!-- fontawesome icon cdn -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.1.1/css/all.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.1.1/css/all.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
<link rel="stylesheet" href="static/style/apxobjmanager.css">
<script> <script>
const apxlocal = { const apxlocal = {
headers: { xalias: "anonymous", xhash: "anonymous", xdays: 0, xtribe: "town", xapp: "adminapx", xlang: "en" }, headers: { xalias: "anonymous", xhash: "anonymous", xdays: 0, xtribe: "town", xapp: "adminapx", xlang: "en" },
@ -36,6 +38,7 @@
<script src="static/js/apxtribes.js"></script> <script src="static/js/apxtribes.js"></script>
<script src="static/js/apxtowns.js"></script> <script src="static/js/apxtowns.js"></script>
<script src="static/js/apxapp.js"></script> <script src="static/js/apxapp.js"></script>
<script src="static/js/apxobjmanager.js"></script>
<style> <style>
.fakeimg { .fakeimg {
height: 200px; height: 200px;
@ -89,8 +92,9 @@
aria-expanded="false">Mayor's Town</a> aria-expanded="false">Mayor's Town</a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li><a class="dropdown-item" add2data tpl="static/tpl/townowner_en.mustache" <li><a class="dropdown-item" add2data tpl="static/tpl/townowner_en.mustache"
onclick="app.load('apxmain','townowner',towns.loadtpldata())">Own this town</a></li> onclick="app.load('apxmain','townowner',towns.loadtpldata('owner'))">Own this town</a></li>
<li><a class="dropdown-item" href="#">Manage Tribes</a></li> <li><a class="dropdown-item" add2data tpl="static/tpl/towntribes_en.mustache"
onclick="app.load('apxmain','towntribes',towns.loadtpldata('tribes'))">Manage Tribes</a></li>
<li><a class="dropdown-item" href="#">Backup Town/Tribes</a></li> <li><a class="dropdown-item" href="#">Backup Town/Tribes</a></li>
<li> <li>
<hr class="dropdown-divider"> <hr class="dropdown-divider">

View File

@ -0,0 +1,27 @@
/*eslint no-undef:0*/
/*eslint-env browser*/
"use strict";
var objman = objman || {};
objman.objedit = (idcomponent,id) => {
const objdoc = document.getElementById(idcomponent);
objdoc.querySelector(".objlist").classList.add("d-none");
objdoc.querySelector(".objitm").classList.remove("d-none");
objdoc.querySelector(".objaddedit").classList.add("hide");
objdoc.querySelector(".inputfilter").classList.add("hide");
objdoc.querySelector(".btnfilter").classList.add("hide");
objdoc.querySelector(".objlistreturn").classList.remove("d-none");
//recupere les data et le schema
};
objman.returnlist = (idcomponent) => {
const objdoc = document.getElementById(idcomponent);
objdoc.querySelector(".objlist").classList.remove("d-none");
objdoc.querySelector(".objitm").classList.add("d-none");
objdoc.querySelector(".objaddedit").classList.remove("hide");
objdoc.querySelector(".inputfilter").classList.remove("hide");
objdoc.querySelector(".btnfilter").classList.remove("hide");
objdoc.querySelector(".objlistreturn").classList.add("d-none");
};

View File

@ -129,7 +129,7 @@ pagans.createIdentity = async (alias, passphrase = "") => {
apx.data.tmp = keys; // to make it available for btn download apx.data.tmp = keys; // to make it available for btn download
document.getElementById("generatekeys").classList.add("d-none"); document.getElementById("generatekeys").classList.add("d-none");
document.getElementById("trustintribe").classList.remove("d-none"); document.getElementById("trustintribe").classList.remove("d-none");
document.getElementById("downloadkeys").classList.remove("d-none"); //document.getElementById("downloadkeys").classList.remove("d-none");
document.getElementById("createId").classList.remove("d-none"); document.getElementById("createId").classList.remove("d-none");
}; };
@ -188,6 +188,12 @@ pagans.registerIdentity = async () => {
.post("api/pagans", data, { headers: apx.data.headers }) .post("api/pagans", data, { headers: apx.data.headers })
.then((reppagan) => { .then((reppagan) => {
console.log(reppagan); console.log(reppagan);
if (reppagan.status==200) {
document.getElementById('downloadkeys').classList.remove('d-none');
alert("Your identity is created, don't forget to download your key")
}else{
alert('Check the console an error appear');
}
}) })
.catch((err) => { .catch((err) => {
console.log("sorry", err); console.log("sorry", err);

View File

@ -4,26 +4,59 @@
"use strict"; "use strict";
var towns = towns || {}; var towns = towns || {};
towns.loadtpldata = () => { towns.loadtpldata = (fortpl) => {
// adapte tpldata to template tpl // adapte tpldata to template tpl
const dataowner = apx.data.tpldata.setup; if (fortpl == "owner") {
dataowner.alias=apx.data.headers.xalias; const dataowner = apx.data.tpldata.setup;
dataowner.auth = dataowner.alias!="anonymous"; dataowner.alias = apx.data.headers.xalias;
dataowner.devtown = dataowner.townId == "devfarm"; dataowner.auth = dataowner.alias != "anonymous";
if (dataowner.mayorid) dataowner.owner = dataowner.mayorid == dataowner.alias; dataowner.devtown = dataowner.townId == "devfarm";
console.log('Data return to template',dataowner) if (dataowner.mayorId)
return dataowner; dataowner.owner = dataowner.mayorId == dataowner.alias;
console.log("Data return to template", dataowner);
return dataowner;
}
if (fortpl == "tribes") {
const data= {
idcomponent: "tribesmanager",
objectname:"tribes",
itm: [
{ tribeId: "tribe1", druidId: "philc" },
{ tribeId: "tribe2", druidId: "toto" },
]
};
data.tplform=`
<div class='mb-3'>
<label for='tribeIdinput' class='form-label'>Tribes Name</label>
<input type='text' class='form-control' id='tribIdinput' placeholder='A unique name'>
</div>
<div class='mb-3'>
<label for='druidIdinput' class='form-label'>Druid Alias</label>
<input type='text' class='form-control' id='druidIdinput' placeholder='An existing alias to become Tribe's Druid'>
</div>
<div class='input-group mb-3 objaction'>
<button class=' objsave btn btn-outline-primary btn-sm' onclick='towns.addupdatetribe('{{tribeId');'><i class='bi-cloud-arrow-up'></i></button>
</div>`;
return data;
}
}; };
towns.owntown = (newowner) => { towns.owntown = (newowner) => {
// only the owner can give ownership to someone else // only the owner can give ownership to someone else
if (!newowner) {newowner=apx.data.headers.xalias} if (!newowner) {
axios.get(`api/towns/changeowner/${newowner}`,{ headers: apx.data.headers }).then(rep=>{ newowner = apx.data.headers.xalias;
console.log(rep) }
apx.data.tpldata.setup.moyorId=newowner; axios
apx.save(); .get(`api/towns/changeowner/${newowner}`, { headers: apx.data.headers })
app.load('apxmain','townowner',towns.loadtpldata()) .then((rep) => {
}).catch(err=>{ console.log(rep);
console.log(err) apx.data.tpldata.setup.mayorId = newowner;
}) apx.save();
app.load("apxmain", "townowner", towns.loadtpldata());
})
.catch((err) => {
console.log(err);
});
}; };
towns.addtribe=(tribeId)=>{
}

View File

@ -0,0 +1,8 @@
.objmanager .list-group-item {
display: flex;
align-items: center;
justify-content: space-between;
}
.objmanager .hide {
visibility: hidden;
}

View File

@ -4,8 +4,8 @@
<p>Step by step </p> <p>Step by step </p>
<div class="input-group mb-3"> <div class="input-group mb-3">
<input class="form-control me-1" type="search" placeholder="Search" aria-label="Search"> <input class="form-control me-1" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-primary" onclick="app.search(this)"> <button class="btn btn-outline-primary btn-sm" onclick="app.search(this)">
<i class="fa-solid fa-magnifying-glass"></i> <i class="bi-search"></i>
</button> </button>
</div> </div>
<h4 class="mt-4">Articles</h4> <h4 class="mt-4">Articles</h4>

View File

@ -20,7 +20,7 @@
{{^mayorId}} {{^mayorId}}
<p> <p>
This town is not own by a mayor, anyone can use a pagan account to tell that he is owning this, so please, This town is not own by a mayor, anyone can use a pagan account to tell that he is owning this, so please,
{{#auth}} you are authenticate under alias: {{alias}} <button class="btn btn-primary" onclick="towns.owntown();">Own this town</button> {{#auth}} you are authenticate under alias: {{alias}} <button class="btn btn-primary" onclick="towns.owntown('{{alias}}');">Own this town</button>
{{/auth}} {{/auth}}
{{^auth}} you have to be authenticat with an alias to own this town. go to Pagan / create login logout and authentify yourself and come back here. {{^auth}} you have to be authenticat with an alias to own this town. go to Pagan / create login logout and authentify yourself and come back here.
{{/auth}} {{/auth}}
@ -30,13 +30,13 @@
{{#devtown}} {{#devtown}}
<p>You need to change town name (by default it is for dev "devfarm") by running on serveur as sudoer user: </p> <p>You need to change town name (by default it is for dev "devfarm") by running on serveur as sudoer user: </p>
<code>node apxtrib.js nationId:nationRequested townId:nameNotalreadyUse dns:domainToAccessTown </code> <code>node apxtrib.js nationId:nationRequested townId:nameNotalreadyUse dns:domainToAccessTown </code>
<p>Come back here.</p> <p>Then Come back here.</p>
{{/devtown}} {{/devtown}}
{{^devtown}} {{^devtown}}
<p> As owner you({{alias}}) can give the ownership of this town to an other alias. Be carefull when you click on this button you lose all your accessright on this town.</p> <p> As owner you({{alias}}) can give the ownership of this town to an other alias. Be carefull when you click on this button you lose all your accessright on this town.</p>
<div class="input-group mb-3"> <div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Give alias to take the ownership" aria-label="New owner alias" aria-describedby="button-chgown"> <input id="newowner" type="text" class="form-control" placeholder="Give alias to take the ownership" aria-label="New owner alias" aria-describedby="button-chgown">
<button class="btn btn-outline-secondary" type="button" id="button-chgown">Give him the role on this town</button> <button class="btn btn-outline-secondary" type="button" id="button-chgown" onclick="towns.owntown(document.getelementbyId('newowner').value)">Give him the role on this town</button>
</div> </div>
{{/devtown}} {{/devtown}}

View File

@ -0,0 +1,42 @@
<div class="container">
<div class="row">
<h4 class="text-center">Manage your tribes</h4>
<div id="{{idcomponent}}" class="col-sm-6 objmanager" >
<div class="row">
<div class="col">
<p>Tribes</p>
</div>
<div class="col text-end">
<div class="input-group mb-3">
<input class="inputfilter form-control me-1" type="search" placeholder="Filter" aria-label="Search">
<button class="btnfilter btn btn-outline-primary btn-sm" onclick="objman.filter('{{idcomponent}}';this)">
<i class="bi-search"></i>
</button>
<button class=" objaddedit btn btn-outline-primary btn-sm" onclick="objman.objedit('{{idcomponent}}');"><i class="bi-plus"></i></button>
<button class=" objaddedit btn btn-outline-primary btn-sm" onclick="objman.objedit('{{schema}}');"><i class="bi-filetype-json"></i></button>
<button class="objlistreturn btn btn-outline-primary btn-sm d-none" onclick="objman.returnlist('{{idcomponent}}')"><i class="bi-list-ul"></i></button>
</div>
</div>
</div>
<div class="objlist">
<ul class="list-group">
{{#itm}}
<li class="list-group-item">
<span>{{tribeId}} ({{druidId}})</span>
<div>
<button class="btn btn-outline-primary btn-sm" onclick="objman.objedit('{{idcomponent}}','{{tribeId}}')"><i class="bi-pen"></i></button>
<button class="btn btn-outline-primary btn-sm" onclick="{{fctdel}}('{{objectname}}',{{tribeId}})"><i class="bi-trash"></i></button>
</div>
</li>
{{/itm}}
</ul>
</div>
<div class="objitm d-none">
{{{tplform}}}
<div class="msgaction"></div>
</div>
</div>
<div class="col-sm-6" >
</div>
</div>
</div>

View File

@ -50,7 +50,7 @@ const checkHeaders = (req, res, next) => {
if (!req.header("xlang") && req.header("Content-Language")) if (!req.header("xlang") && req.header("Content-Language"))
req.params.xlang = req.header("Content-Language"); req.params.xlang = req.header("Content-Language");
let missingheader = []; let missingheader = [];
console.log("req.headers", req.headers); //console.log("req.headers", req.headers);
for (const h of conf.api.exposedHeaders) { 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]) {

View File

@ -11,6 +11,7 @@ Checkjson.schema = {};
Checkjson.schema.properties = {}; Checkjson.schema.properties = {};
Checkjson.schema.properties.type = {}; Checkjson.schema.properties.type = {};
Checkjson.schema.properties.type.string = (str) => typeof str === "string"; Checkjson.schema.properties.type.string = (str) => typeof str === "string";
Checkjson.schema.properties.type.array = (val)=> Array.isArray(val);
Checkjson.schema.properties.type.number = (n) => typeof n === "number"; Checkjson.schema.properties.type.number = (n) => typeof n === "number";
Checkjson.schema.properties.type.boolean = (n) => typeof n === "boolean"; Checkjson.schema.properties.type.boolean = (n) => typeof n === "boolean";
Checkjson.schema.properties.type.integer = (n) => Checkjson.schema.properties.type.integer = (n) =>
@ -46,8 +47,9 @@ Checkjson.schema.properties.range = (
}; };
Checkjson.schema.properties.pattern = (str, pattern) => { Checkjson.schema.properties.pattern = (str, pattern) => {
try { try {
new RegExp(pattern); pattern= new RegExp(pattern);
} catch (e) { } catch (e) {
console.log('err pattern in checkjon',pattern);
return false; return false;
} }
return pattern.test(str); return pattern.test(str);
@ -56,10 +58,10 @@ Checkjson.schema.properties.enum = (str, enumvalues) =>
typeof str === "string" && enumvalues.includes(str); typeof str === "string" && enumvalues.includes(str);
// see format https://json-schema.org/understanding-json-schema/reference/string.html#format // see format https://json-schema.org/understanding-json-schema/reference/string.html#format
Checkjson.schema.properties.format = { Checkjson.schema.properties.format = {
"date-time": / /, "date-time": /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d{1,3}/,
stringalphaonly:/^[A-Za-z0-9]{3,}$/, stringalphaonly:/^[A-Za-z0-9]{3,}$/,
time: / /, time: /[0-2]\d:[0-5]\d:[0-5]\d\.\d{1,3}/,
date: / /, date: /\d{4}-[01]\d-[0-3]\d/,
duration: / /, duration: / /,
email: email:
/^(([^<>()[\]\\.,;:\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,}))$/, /^(([^<>()[\]\\.,;:\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,}))$/,
@ -91,8 +93,9 @@ Checkjson.schema.validation = (schema) => {
!Checkjson.schema.properties.type[properties[p].type] !Checkjson.schema.properties.type[properties[p].type]
) { ) {
res.err.push({ res.err.push({
info: "|Checkjson|typedoesnotexistinschema", ref:"Checkjson",
moreinfo: ` ${properties[p].type}`, msg:"schemaerrtypedoesnotexist",
data: {propertie:p,type:properties[p].type}
}); });
} }
if ( if (
@ -103,8 +106,9 @@ Checkjson.schema.validation = (schema) => {
properties[p].type.forEach((tp) => { properties[p].type.forEach((tp) => {
if (!Checkjson.schema.properties.type[tp]) if (!Checkjson.schema.properties.type[tp])
res.err.push({ res.err.push({
info: "|Checkjson|typedoesnotexistinschema", ref:"Checkjson",
moreinfo: `${tp} of ${properties[p].type}`, msg:"schemaerrtypedoesnotexist",
data: {propertie:p,type:properties[p].type}
}); });
}); });
} }
@ -113,14 +117,16 @@ Checkjson.schema.validation = (schema) => {
!Checkjson.schema.properties.format[properties[p].format] !Checkjson.schema.properties.format[properties[p].format]
) { ) {
res.err.push({ res.err.push({
info: "|Checkjson|formatdoesnotexistinschema", ref:"Checkjson",
moreinfo: ` ${properties[p].format}`, msg:"schemaerrformatdoesnotexist",
data: {propertie:p,format:properties[p].format}
}); });
} }
if (properties[p].enum && !Array.isArray(properties[p].enum)) { if (properties[p].enum && !Array.isArray(properties[p].enum)) {
res.err.push({ res.err.push({
info: "|Checkjson|enumisnotarrayinschema", ref:"Checkjson",
moreinfo: ` ${properties[p].enum}`, msg:"schemaerrenumnotarray",
data: {propertie:p,enum:properties[p].enum}
}); });
} }
}); });
@ -159,8 +165,9 @@ Checkjson.schema.data = (schema, data, withschemacheck) => {
}); });
if (!valid) if (!valid)
res.err.push({ res.err.push({
info: "|Checkjson|dataerrpropertie", ref:"Checkjson",
moreinfo: `${p} : ${data[p]}`, msg:"dataerrpropertie",
data: {key:p,value:data[p]}
}); });
if ( if (
@ -168,17 +175,19 @@ Checkjson.schema.data = (schema, data, withschemacheck) => {
!Checkjson.schema.properties.minLength(data[p], properties[p].minLength) !Checkjson.schema.properties.minLength(data[p], properties[p].minLength)
) { ) {
res.err.push({ res.err.push({
info: "|Checkjson|dataerrpropertie", ref:"Checkjson",
moreinfo: `${p} : ${data[p]} minLength:${properties[p].minLength}`, msg:"dataerrpropertie",
}); data:{key:p,value:data[p],minLength:properties[p].minLength}
});
} }
if ( if (
properties[p].maxLength && properties[p].maxLength &&
!Checkjson.schema.properties.maxLength(data[p], properties[p].maxLength) !Checkjson.schema.properties.maxLength(data[p], properties[p].maxLength)
) { ) {
res.err.push({ res.err.push({
info: "|Checkjson|dataerrpropertie", ref:"Checkjson",
moreinfo: `${p} : ${data[p]} maxLength:${properties[p].maxLength}`, msg:"dataerrpropertie",
data:{key:p,value:data[p],maxLength:properties[p].maxLength}
}); });
} }
if ( if (
@ -186,8 +195,9 @@ Checkjson.schema.data = (schema, data, withschemacheck) => {
!Checkjson.schema.properties.multipleOf(data[p], properties[p].multipleOf) !Checkjson.schema.properties.multipleOf(data[p], properties[p].multipleOf)
) { ) {
res.err.push({ res.err.push({
info: "|Checkjson|dataerrpropertie", ref:"Checkjson",
moreinfo: `${p} : ${data[p]} not a multipleOf:${properties[p].multipleOf}`, msg:"dataerrpropertie",
data:{key:p,value:data[p],multipleOf:properties[p].multipleOf}
}); });
} }
if ( if (
@ -207,8 +217,9 @@ Checkjson.schema.data = (schema, data, withschemacheck) => {
) )
) { ) {
res.err.push({ res.err.push({
info: "|Checkjson|dataerrpropertie", ref:"Checkjson",
moreinfo: `${p} : ${data[p]} not in range ${properties[p].minimum} exclu: ${properties[p].exclusiveMinimum} and ${properties[p].maximum} exclu: ${properties[p].exclusiveMaximum}`, msg:"dataerrpropertie",
data:{key:p,value:data[p],minimum:properties[p].minimum,maximum:properties[p].maximum,exclusiveMinimum:properties[p].exclusiveMinimum,exclusiveMaximum:properties[p].exclusiveMaximum}
}); });
} }
} }
@ -217,8 +228,9 @@ Checkjson.schema.data = (schema, data, withschemacheck) => {
!Checkjson.schema.properties.enum(data[p], properties[p].enum) !Checkjson.schema.properties.enum(data[p], properties[p].enum)
) { ) {
res.err.push({ res.err.push({
info: "|Checkjson|dataerrpropertie", ref:"Checkjson",
moreinfo: `${p} : ${data[p]} not in enum list :${properties[p].enum}`, msg:"dataerrpropertie",
data:{key:p,value:data[p],enumlst:properties[p].enum}
}); });
} }
if (properties[p].format) { if (properties[p].format) {
@ -230,14 +242,16 @@ Checkjson.schema.data = (schema, data, withschemacheck) => {
!Checkjson.schema.properties.pattern(data[p], properties[p].pattern) !Checkjson.schema.properties.pattern(data[p], properties[p].pattern)
) { ) {
res.err.push({ res.err.push({
info: "|Checkjson|dataerrpropertie", ref:"Checkjson",
moreinfo: `${p} : ${data[p]} problem pattern or format ${properties[p].pattern}`, msg:"dataerrpropertie",
data:{key:p,value:data[p],pattern:properties[p].pattern}
}); });
} }
} else if (schema.required && schema.required.includes(p)) { } else if (schema.required && schema.required.includes(p)) {
res.err.push({ res.err.push({
info: "|Checkjson|dataerrpropertiesrequired", ref:"Checkjson",
moreinfo: `${p}`, msg:"dataerrpropertierequired",
data:{key:p,required:true}
}); });
} }
}); });

View File

@ -42,7 +42,7 @@ Nations.updateobjectsfromfreshesttown = (dnstownlist, objectidx) => {
objlist.forEach((o) => { objlist.forEach((o) => {
let objconf = { let objconf = {
name: o, name: o,
schema: `nationchains/schema/${o}.jsons`, schema: `adminapi/schema/${o}.jsons`,
lastupdate: -1, lastupdate: -1,
}; };
if (fs.existsSync(`${conf.dirapi}/nationchains/${o}/conf.json`)) { if (fs.existsSync(`${conf.dirapi}/nationchains/${o}/conf.json`)) {
@ -54,62 +54,64 @@ Nations.updateobjectsfromfreshesttown = (dnstownlist, objectidx) => {
}); });
//console.log(localversion); //console.log(localversion);
for (let t = 0; t < dnstownlist.length; t++) { for (let t = 0; t < dnstownlist.length; t++) {
let promiseconf = []; if (conf.townId != dnstownlist[t].townId) { // to avoid update itself
let objecttotest = []; let promiseconf = [];
objlist.forEach((o) => { let objecttotest = [];
//console.log(`https://${dnstownlist[t].dns}/nationchains/${o}/conf.json`); objlist.forEach((o) => {
objecttotest.push(o); //console.log(`https://${dnstownlist[t].dns}/nationchains/${o}/conf.json`);
promiseconf.push( objecttotest.push(o);
axios.get(`https://${dnstownlist[t].dns}/nationchains/${o}/conf.json`) promiseconf.push(
); axios.get(`https://${dnstownlist[t].dns}/nationchains/${o}/conf.json`)
}); );
Promise.all(promiseconf) });
.then((reps) => { Promise.all(promiseconf)
let promiseidx = []; .then((reps) => {
let objecttoupdate = []; let promiseidx = [];
let objlastupdate = []; let objecttoupdate = [];
for (let i = 0; i < objecttotest.length; i++) { let objlastupdate = [];
if ( for (let i = 0; i < objecttotest.length; i++) {
parseInt(reps[i].data.lastupdate) > if (
parseInt(localversion[reps[i].data.name][1]) parseInt(reps[i].data.lastupdate) >
) { parseInt(localversion[reps[i].data.name][1])
// add promise to get data ) {
/*console.log( // add promise to get data
/*console.log(
`https://${dnstownlist[t].dns}/nationchains/${ `https://${dnstownlist[t].dns}/nationchains/${
reps[i].data.name reps[i].data.name
}/idx/${objectidx[reps[i].data.name]}` }/idx/${objectidx[reps[i].data.name]}`
);*/ );*/
objecttoupdate.push(objecttotest[i]); objecttoupdate.push(objecttotest[i]);
objlastupdate.push(reps[i].data.lastupdate); objlastupdate.push(reps[i].data.lastupdate);
promiseidx.push( promiseidx.push(
axios.get( axios.get(
`https://${dnstownlist[t].dns}/nationchains/${ `https://${dnstownlist[t].dns}/nationchains/${
reps[i].data.name reps[i].data.name
}/idx/${objectidx[reps[i].data.name]}` }/idx/${objectidx[reps[i].data.name]}`
) )
);
}
}
Promise.all(promiseidx)
.then((rets) => {
for (let j = 0; j < objecttoupdate.length; j++) {
Odmdb.updatefromidxall(
objecttoupdate[j],
objectidx[objecttoupdate[j]],
rets[j].data,
objlastupdate[j]
); );
} }
}) }
.catch((err) => { Promise.all(promiseidx)
console.log("ERR get idx data"); .then((rets) => {
console.log(err); for (let j = 0; j < objecttoupdate.length; j++) {
}); Odmdb.updatefromidxall(
}) objecttoupdate[j],
.catch((err) => { objectidx[objecttoupdate[j]],
console.log("ERR get conf lastupdate"); rets[j].data,
console.log(err); objlastupdate[j]
}); );
}
})
.catch((err) => {
console.log("ERR get idx data");
console.log(err);
});
})
.catch((err) => {
console.log("ERR get conf lastupdate");
console.log(err);
});
}
} }
}; };
Nations.synchronizeold = () => { Nations.synchronizeold = () => {

View File

@ -2,6 +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 dayjs = require("dayjs"); const dayjs = require("dayjs");
const axios = require("axios");
const conf = require(`${process.env.dirtown}/conf.json`); const conf = require(`${process.env.dirtown}/conf.json`);
const Checkjson = require(`./Checkjson.js`); const Checkjson = require(`./Checkjson.js`);
@ -148,7 +149,7 @@ Odmdb.schema = (schemaPath, objectName, withschemacheck) => {
}; };
}; };
Odmdb.Checkjson = (objectPath, objectName, data, withschemacheck) => { //Odmdb.Checkjson = (objectPath, objectName, data, withschemacheck) => {
/* /*
@objectPath path to the folder that contain /objects/objectName/ /lg/objectName_{lg}.json /schema/objectName.json @objectPath path to the folder that contain /objects/objectName/ /lg/objectName_{lg}.json /schema/objectName.json
@objectName name of object @objectName name of object
@ -161,19 +162,18 @@ Odmdb.Checkjson = (objectPath, objectName, data, withschemacheck) => {
or unconsitent data and schema from Checkjson.js Checkjson.schema.data or unconsitent data and schema from Checkjson.js Checkjson.schema.data
*/ */
const res = { status: 200 }; /* const res = { status: 200,ref="Odmdb",msg:"",data:{} };
//get schema link of object //get schema link of object
const schemaPath = fs.readJsonSync( const schemaPath = fs.readJsonSync(
`${objectPath}/${objectName}/idx/confjson` `${objectPath}/${objectName}/idx/conf.json`
)["schema"]; )["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 {
schema == "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; res.data.schema = Odmdb.schema(objectPath, objectName, withschemacheck);
} }
// check schema validity // check schema validity in case withschemacheck
const schema = Odmdb.schema(objectPath, objectName, withschemacheck); if (schema.status != 200) return ;
if (schema.status != 200) return schema;
console.log("SCHEMA for checking:"); console.log("SCHEMA for checking:");
console.log(schema.data); console.log(schema.data);
console.log("DATA to check:"); console.log("DATA to check:");
@ -207,6 +207,43 @@ Odmdb.Checkjson = (objectPath, objectName, data, withschemacheck) => {
} }
return res; return res;
}; };
*/
Odmdb.getSchema=async (schemaPath,validschema)=>{
/**
* @schemaPath public http link or local path adminapi/schema/objectName.json or /tribename/schema/objectName
* @return schema or {}
*/
const res={status:200,data:{schema:{}}}
if (schemaPath.slice(-5)!=".json") schemaPath+=".json";
if (schemaPath.substring(0, 4) == "http") {
// lance requete http pour recuperer le schema avec un await axios
} else {
if (schemaPath.substring(0,9)=="adminapi/"){
schemaPath=`${conf.dirapi}/${schemaPath}`
}else{
schemaPath=`${conf.dirtown}/tribes/${schemaPath}`
}
if (!fs.existsSync(schemaPath)){
return {status:404, ref:"Odmdb", msg:"schemanotfound", data:{schemaPath,schema:{}}}
}
res.data.schema=fs.readJsonSync(schemaPath)
if (validschema ||1==1){
const check = Checkjson.schema.validation(res.data.schema)
if (check.err.length>0) {
res.status=check.status
res.data.err=check.err
}
//check json schema for Odmdb context
if (!res.data.schema.apxprimarykey || !res.data.schema.properties[res.data.schema.apxprimarykey]){
// primarykey require for Odmdb
res.status=406
if (!res.data.err) res.data.err=[];
res.data.err.push({ref:"Odmdb",msg:"novalidprimarykey",data:{apxprimarykey:res.data.schema.apxprimarykey}})
}
}
}
return res
}
Odmdb.search = (objectPath, objectName, search) => { Odmdb.search = (objectPath, objectName, search) => {
/* /*
@search= { @search= {
@ -228,51 +265,78 @@ Odmdb.search = (objectPath, objectName, search) => {
}; };
Odmdb.get = (objectPath, objectName, uuidprimarykeyList, fieldList) => { Odmdb.get = (objectPath, objectName, uuidprimarykeyList, fieldList) => {
/* /*
@objectPath where object are store (where /object/conf.json indicate where the schema is)
@uuidprimarykeyList list of uuid requested @uuidprimarykeyList list of uuid requested
@fieldList key to return for each object @fieldList key to return for each object
Return objectName {status:200; data:{found:[{primarykey,field}],notfound:[uuid]} Return {status:200; data:{uuid:{data filter by @fieldList},uuid:"notfound"}}
if all primarykey exist then data.notfound does not exist
if all primarykey does not exist data.found does not exist
*/ */
const res = { status: 200, data: {} }; const res = { status: 200, data: {} };
uuidprimarykeyList.forEach((id) => { uuidprimarykeyList.forEach(id => {
if (fs.existsSync(`${objectPath}/${objectName}/${id}.json`)) { if (fs.existsSync(`${objectPath}/${objectName}/itm/${id}.json`)) {
if (!res.data.found) res.data.found = [];
const objectdata = fs.readJsonSync( const objectdata = fs.readJsonSync(
`${objectPath}/${objectName}/${id}.json` `${objectPath}/${objectName}/itm/${id}.json`
); );
if (!fieldList) { if (!fieldList) {
res.data.found.push(objectdata); res.data[id]=objectdata;
} else { } else {
const objinfo = {}; const objinfo = {};
fieldlList.forEach((k) => { fieldlList.forEach((k) => {
if (objectdata[k]) objinfo[k] = objectdata[k]; if (objectdata[k]) objinfo[k] = objectdata[k];
}); });
res.data.found.push(objinfo); res.data[id]=objinfo;
} }
} else { } else {
if (!res.data.notfound) res.data.notfound = []; res.data[id]="notfound";
} }
}); });
return res; return res;
}; };
Odmdb.create = (objectPath, objectName, data) => { Odmdb.create = (objectPath, objectName, data, accessright) => {
/* /*
Create an objects data into objectName Create an objects data into objectName
@objectPath path to the folder that contain /objects/objectName/ /objectsInfo/objectName_lg.json /objectsMeta/objectName.json @objectPath path to the folder that contain /objects/objectName/ /objectsInfo/objectName_lg.json /objectsMeta/objectName.json
@objectName name of object @objectName name of object
@data data to check based on objectsMeta definition @data data to check based on objectsMeta definition
@accessright a string with accessright of the user on this objectName ex: "CRUDO" or "R" or "O"
*/ */
}; };
Odmdb.update = (objectPath, objectName, data) => { Odmdb.update = async (objectPath, objectName, data, id, accessright) => {
/* /*
Create an objects data into objectName Create an objects data into objectName
@objectPath path to the folder that contain /objects/objectName/ /objectsInfo/objectName_lg.json /objectsMeta/objectName.json @objectPath path to the folder that contain /objects/objectName/ /objectsInfo/objectName_lg.json /objectsMeta/objectName.json
@objectName name of object @objectName name of object
@data data to check based on objectsMeta definition @data data to check based on objectsMeta definition
*/ */
if (!fs.existsSync(`${objectPath}/${objectName}/itm/${id}.json`)){
return {status:404,ref:"Odmdb",msg:"itmnotfound",data:{objectPath,objectName,id}}
}
const currentobj=fs.readJSONSync(`${objectPath}/${objectName}/itm/${id}.json`)
Object.keys(data).forEach(k=>{
currentobj[k]=data[k]
})
if (currentobj.dt_update) currentobj.dt_update=dayjs().toISOString();
const schemaPath = fs.readJsonSync(
`${objectPath}/${objectName}/conf.json`
)["schema"];
const getschema = await Odmdb.getSchema(schemaPath);
if (getschema.status!=200 || Object.keys(getschema.data.schema).length==0) {
console.log('this is not suppose to happen in Odmdb',Object.keys(getschema.data.schema))
return getschema
}
const schema=getschema.data.schema;
const check = Checkjson.schema.data(schema,currentobj,false);
console.log(check)
if (check.err.length==0){
// update
fs.outputJsonSync(`${objectPath}/${objectName}/itm/${id}.json`,currentobj)
//@todo select index file to generate depending of k update currently we re-index all
return {status:200,ref:"Odmdb",msg:"updatesuccessfull"}
}else{
return {status:409, ref:"Odmdb",msg:"datavsschemaunconsistent",data:check.err}
}
}; };
Odmdb.delete = (objectPath, objectName, data) => { Odmdb.delete = (objectPath, objectName, data,accessright) => {
/* /*
Create an objects data into objectName Create an objects data into objectName
@objectPath path to the folder that contain /objects/objectName/ /objectsInfo/objectName_lg.json /objectsMeta/objectName.json @objectPath path to the folder that contain /objects/objectName/ /objectsInfo/objectName_lg.json /objectsMeta/objectName.json
@ -313,7 +377,8 @@ Odmdb.updatefromidxall = (objectname, idxname, data, lastupdate) => {
localidx[id].dt_update > data[id].dt_update localidx[id].dt_update > data[id].dt_update
) { ) {
// means local information is fresher than the one in data for replacement // means local information is fresher than the one in data for replacement
conflastupdate = dayjs(); // .toISIString ex: 2019-01-25T02:00:00.000Z'
conflastupdate = dayjs().toISOString();
} else { } else {
// replace itm with data // replace itm with data
localidx[id] = data[id]; localidx[id] = data[id];

View File

@ -86,9 +86,9 @@ Pagans.create = (alias, publicKey) => {
* @todo use Odmdb to add a pagan * @todo use Odmdb to add a pagan
*/ */
let apxpagans = {}; let apxpagans = {};
if (fs.existsSync(`${__dirapi}/nationchains/pagans/idx/alias_all.json`)) { if (fs.existsSync(`${conf.dirapi}/nationchains/pagans/idx/alias_all.json`)) {
apxpagans = fs.readJsonSync( apxpagans = fs.readJsonSync(
`${__dirapi}/nationchains/pagans/idx/alias_all.json` `${conf.dirapi}/nationchains/pagans/idx/alias_all.json`
); );
} }
apxpagans[alias] = { alias, publicKey }; apxpagans[alias] = { alias, publicKey };
@ -100,7 +100,7 @@ Pagans.create = (alias, publicKey) => {
alias, alias,
publicKey, publicKey,
}); });
return { status: 200, data: { alias, publicKey } }; return { status: 200, ref:"Pagans", msg:"identitycreate",data: { alias, publicKey } };
}; };
Pagans.personupdate = (alias, tribe, persondata) => { Pagans.personupdate = (alias, tribe, persondata) => {

View File

@ -6,9 +6,141 @@ const jwt = require("jwt-simple");
const UUID = require("uuid"); const UUID = require("uuid");
const conf = require(`${process.env.dirtown}/conf.json`); const conf = require(`${process.env.dirtown}/conf.json`);
const Checkjson = require(`./Checkjson.js`); const Checkjson = require(`./Checkjson.js`);
const Odmdb = require("./Odmdb.js");
const Towns = {}; const Towns = {};
Towns.changeowner = (newowner, requestby) => {
Towns.create = () => {
// Create a new town from conf (generate in apxtribe.js if town not already exist in the server)
console.log(
`RUNNING A NEW SETUP with nation ${conf.nationId} and town ${conf.townId} to be accessible in dns http://${conf.dns}`
);
const initconf = fs.readJSONSync(
`${conf.dirapi}/adminapi/www/adminapx/initconf.json`
);
// Synchronize nationchains/
const { updateobjectsfromfreshesttown } = require("./api/models/Nations.js");
updateobjectsfromfreshesttown(initconf.towns, {
pagans: "alias_all.json",
towns: "townId_all.json",
nations: "nationId_all.json",
});
initconf.dirapi = conf.dirapi;
initconf.dirtown = conf.dirtown;
initconf.nationId = conf.nationId;
initconf.townId = conf.townId;
initconf.sudoerUser = process.env.USER;
if (!initconf.dns.includes(conf.dns)) {
initconf.dns.push(conf.dns);
}
initconf.nginx.include.push(`${initconf.dirapi}/adminapi/www/nginx_*.conf`);
initconf.nginx.include.push(`${initconf.dirtown}/tribes/**/www/nginx_*.conf`);
initconf.nginx.logs = `${initconf.dirtown}/logs/nginx/adminapx`;
fs.ensureDirSync(`${initconf.dirtown}/logs/nginx`);
fs.ensureDirSync(`${initconf.dirtown}/tmp/tokens`);
initconf.nginx.website = "adminapx";
initconf.nginx.fswww = `${initconf.dirapi}/adminapi/www`;
initconf.nginx.pageindex = "index_en.html";
const { exec } = require("child_process");
exec(
`sudo chown -R ${process.env.USER}:${process.env.USER} /etc/nginx`,
(error, stdout, stderr) => {
if (error) {
console.log("\x1b[42m", error, stdout, stderr, "x1b[0m");
console.log(
`impossible to change owner of /etc/nginx by ${initconf.sudoerUser}:${initconf.sudoerUser}`
);
fs.removeSync(initconf.dirtown);
process.exit();
} else {
console.log(
`successfull sudo chown -R ${process.env.USER}:${process.env.USER} /etc/nginx`
);
}
}
);
// create town env
fs.outputJsonSync(`${initconf.dirtown}/conf.json`, initconf, { space: 2 });
const nginxconf = fs.readFileSync(
"./adminapi/www/adminapx/conf/nginx.conf.mustache",
"utf8"
);
const proxyparams = fs.readFileSync(
"./adminapi/www/adminapx/conf/nginxproxyparams.mustache",
"utf8"
);
const websiteconf = fs.readFileSync(
"./adminapi/www/adminapx/conf/nginxmodelwebsite.conf.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, initconf),
"utf8"
);
fs.outputFileSync(
"/etc/nginx/proxy_params",
mustache.render(proxyparams, initconf),
"utf8"
);
fs.outputFileSync(
`${initconf.dirapi}/adminapi/www/nginx_adminapx.conf`,
mustache.render(websiteconf, initconf),
"utf8"
);
exec(initconf.nginx.restart, (error, stdout, stderr) => {
if (error) {
console.log("\x1b[42m", error, stdout, stderr, "x1b[0m");
//@todo supprimer la derniere config nginx et relancer
fs.moveSync("/etc/nginx/nginxconf.saved", "/etc/nginx/nginx.conf");
console.log("Restart yarn dev with correct parameter");
// cleanup
fs.removeSync(initconf.dirtown);
} else {
//@TODO à finaliser en test sur machien pour creation de nouvelles villes
// add town in nationchains
const gettown = Odmdb.get(`${initconf.dirapi}/nationchains`, "towns", [
initconf.townId,
]);
if (gettown.data[initconf.townId] == "notfound") {
Odmdb.create(
`${initconf.dirapi}/nationschains`,
"towns",
{
townId: initconf.townId,
nationId: initconf.nationId,
dns: initconf.dns,
IP: "127.0.0.1",
status: "unchain",
tribes: [],
},
false
);
} else if (gettown.data[initconf.townId].dns !== initconf.dns) {
//reinstallation d'une town sur un autre serveur maj du dns , l'ip le status et les tribes se mettent à jour via l'interface
const updtown = Odmdb.update(
`${initconf.dirapi}/nationchains`,
"towns",
{ dns: initconf.dns },
initconf.townId
);
}
console.log(`ready to use http://${initconf.dns}`);
}
});
};
Towns.changeowner = async (newowner, requestby) => {
/** /**
* *
*/ */
@ -21,16 +153,47 @@ Towns.changeowner = (newowner, requestby) => {
}; };
} }
if (!conf.mayorId || conf.mayorId == requestby) { if (!conf.mayorId || conf.mayorId == requestby) {
// update object town + town/conf.json + setup_xx.json // update object town + town/conf.json + setup_xx.json
const gettown = Odmdb.get(`${conf.dirapi}/nationchains`, "towns", [
conf.townId,
]);
console.log(`before town: ${conf.townId}`, gettown);
if (gettown.data[conf.townId] == "notfound") {
return {
status: 404,
ref: "towns",
msg: "townIdnotfound",
data: { townId: conf.townId },
};
}
gettown.data[conf.townId].mayorId = newowner;
const objup = await Odmdb.update(
`${conf.dirapi}/nationchains`,
"towns",
gettown.data[conf.townId],
conf.townId
);
//update the itm town
if (objup.status != 200) {
return objup;
}
console.log(`after town update: ${conf.townId}`, gettown);
conf.mayorId = newowner; conf.mayorId = newowner;
fs.outputJsonSync(`${process.env.dirtown}/conf.json`, conf); fs.outputJsonSync(`${process.env.dirtown}/conf.json`, conf);
const setup = fs.readJSONSync(`${dirapi}/adminapi/www/adminapx/conf/setup_xx.json`) const setup = fs.readJSONSync(
setup.mayorId=newowner; `${conf.dirapi}/adminapi/www/adminapx/conf/setup_xx.json`
fs.outputJsonSync(`${dirapi}/adminapi/www/adminapx/conf/setup_xx.json`,setup); );
conf.mayorId = newowner;
//update the setup file for webapp adminapi
fs.outputJsonSync(
`${conf.dirapi}/adminapi/www/adminapx/conf/setup_xx.json`,
setup
);
return { return {
status: 200, status: 200,
ref: "towns", ref: "towns",
msg: "newownerchangesusccess", msg: "newownerchangesuccess",
data: { alias: newowner }, data: { alias: newowner },
}; };
} }

View File

@ -114,7 +114,7 @@ router.post("/", checkHeaders, isAuthenticated, (req, res) => {
* - check that alias does not already exist (if yes then verifiedsigne would be false) * - 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 * Need to wait next block chain to be sure that alias is register in the blokchain
*/ */
console.log("pass ici", req.body); //console.log("pass ici", req.body);
const feedback = { alias: req.body.alias, publickey: req.body.publickey }; const feedback = { alias: req.body.alias, publickey: req.body.publickey };
const newpagan = Pagans.create(req.body.alias, req.body.publickey); const newpagan = Pagans.create(req.body.alias, req.body.publickey);
if (newpagan.status == 200) { if (newpagan.status == 200) {
@ -136,20 +136,29 @@ router.post("/", checkHeaders, isAuthenticated, (req, res) => {
if (req.app.locals.tribeids.includes(req.body.trustedtribe)) { if (req.app.locals.tribeids.includes(req.body.trustedtribe)) {
delete feedback.withemail; delete feedback.withemail;
const persondata = { recovery: feedback }; const persondata = { recovery: feedback };
res.send( const persoup = Pagans.personupdate(req.body.alias, req.body.trustedtribe, persondata)
res.status(persoup.status).json(persoup)
/*res.send(
Pagans.personupdate(req.body.alias, req.body.trustedtribe, persondata) Pagans.personupdate(req.body.alias, req.body.trustedtribe, persondata)
); );*/
} else { } else {
res.send({ res.status(404).json({
status: 404, status:404,
ref: "Pagans", ref: "Pagans",
msg: "tribedoesnotexist", msg: "tribedoesnotexist",
data: { tribe: req.body.trustedtribe }, data: { tribe: req.body.trustedtribe },
}); });
/*res.send({
status: 404,
ref: "Pagans",
msg: "tribedoesnotexist",
data: { tribe: req.body.trustedtribe },
});*/
} }
} else { } else {
newpagan.data = feedback; newpagan.data = feedback;
res.send(newpagan); res.status(newpagan.status).json(newpagan);
//res.send(newpagan);
} }
} else { } else {
//error to create pagan //error to create pagan
@ -166,10 +175,9 @@ router.put("/person", checkHeaders, isAuthenticated, (req, res) => {
* add/update a person = alias + tribe with specific accessright and specific schema link to tribe * add/update a person = alias + tribe with specific accessright and specific schema link to tribe
* @todo add tribe/schema/person.json * @todo add tribe/schema/person.json
*/ */
console.log(req.body); //console.log(req.body);
res.send( const persoup = Pagans.personupdate(req.body.alias, req.session.header.xtribe, req.body);
Pagans.personupdate(req.body.alias, req.session.header.xtribe, req.body) res.status(persoup.status).json(persoup);
);
}); });
router.delete("/:alias", checkHeaders, isAuthenticated, (req, res) => { router.delete("/:alias", checkHeaders, isAuthenticated, (req, res) => {
/** /**

View File

@ -22,8 +22,10 @@ router.get("/changeowner/:alias",checkHeaders, isAuthenticated, (req, res) => {
* @apiError (404) {object} {ref:"towns",msg:"aliasnotallow",data: { alias} } * @apiError (404) {object} {ref:"towns",msg:"aliasnotallow",data: { alias} }
* *
**/ **/
res.send(Towns.changeowner(req.params.alias, req.session.header.alias)); res.send(Towns.changeowner(req.params.alias, req.session.header.xalias));
}); });
//=======================================================================================
router.get("/person/:alias", checkHeaders, isAuthenticated, (req, res) => { router.get("/person/:alias", checkHeaders, isAuthenticated, (req, res) => {
/** /**
* @api {get} /pagans/person:alias * @api {get} /pagans/person:alias

View File

@ -39,125 +39,6 @@ To share configuration :
* A folder for town data is created at the same level than apxtrib as /townId-nationId/conf.json ... * A folder for town data is created at the same level than apxtrib as /townId-nationId/conf.json ...
*/ */
const setconf = (param) => {
// set conf from argv = param={nationId,townId,dns}
console.log(
`RUNNING A NEW SETUP with nation ${param.nationId} and town ${param.townId} to be accessible in dns http://${param.dns}`
);
fs.outputJsonSync(
`${__dirname}/adminapi/www/adminapx/conf/setup_xx.json`,
{
nationId: param.nationId,
townId: param.townId,
dns: [param.dns],
comment:
"Auto generate setup from apxtrib after node apxtrib nationId:value townId:value dns:domaine_to_access",
},
{ space: 2 }
);
// Add this town localy
const townid = {
townId: param.townId,
nationId: param.nationId,
dns: param.dns,
IP: "127.0.0.1",
status: "unchain",
tribes: [],
};
const townidkey = {};
townidkey[param.townId] = townid;
fs.outputJsonSync(`./nationchains/towns/idx/townId_all.json`, townidkey);
fs.outputJsonSync(`./nationchains/towns/itm/${param.townId}.json`, townid);
initconf = fs.readJsonSync("./adminapi/www/adminapx/conf/initconf.json");
initconf.dirapi = __dirname;
initconf.dirtown = path.resolve(
`${__dirname}/../${param.townId}-${param.nationId}`
);
initconf.nationId = param.nationId;
initconf.townId = param.townId;
initconf.sudoerUser = process.env.USER;
if (!initconf.dns.includes(param.dns)) {
initconf.dns.push(param.dns);
}
initconf.nginx.include.push(`${initconf.dirapi}/adminapi/www/nginx_*.conf`);
initconf.nginx.include.push(
path.resolve(
`../${param.townId}-${param.nationId}/tribes/**/www/nginx_*.conf`
)
);
initconf.nginx.logs = `${initconf.dirtown}/logs/nginx/adminapx`;
initconf.nginx.website = "adminapx";
initconf.nginx.fswww = `${__dirname}/adminapi/www`;
initconf.nginx.pageindex = "index_en.html";
const { exec } = require("child_process");
exec(
`sudo chown -R ${process.env.USER}:${process.env.USER} /etc/nginx`,
(error, stdout, stderr) => {
if (error) {
console.log("\x1b[42m", error, stdout, stderr, "x1b[0m");
console.log("impossible to change owner of /etc/nginx by phil:phil");
process.exit();
} else {
console.log(
`successfull sudo chown -R ${process.env.USER}:${process.env.USER} /etc/nginx`
);
}
}
);
fs.outputJsonSync(
`../${param.townId}-${param.nationId}/conf.json`,
initconf,
{ space: 2 }
);
fs.ensureDirSync(`../${param.townId}-${param.nationId}/logs/nginx`);
fs.ensureDirSync(`../${param.townId}-${param.nationId}/tmp/tokens`);
const nginxconf = fs.readFileSync(
"./adminapi/www/adminapx/conf/nginx.conf.mustache",
"utf8"
);
const proxyparams = fs.readFileSync(
"./adminapi/www/adminapx/conf/nginxproxyparams.mustache",
"utf8"
);
const websiteconf = fs.readFileSync(
"./adminapi/www/adminapx/conf/nginxmodelwebsite.conf.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, initconf),
"utf8"
);
fs.outputFileSync(
"/etc/nginx/proxy_params",
mustache.render(proxyparams, initconf),
"utf8"
);
fs.outputFileSync(
`${__dirname}/adminapi/www/nginx_adminapx.conf`,
mustache.render(websiteconf, initconf),
"utf8"
);
exec(initconf.nginx.restart, (error, stdout, stderr) => {
if (error) {
console.log("\x1b[42m", error, stdout, stderr, "x1b[0m");
//@todo supprimer la derniere config nginx et relancer
fs.moveSync("/etc/nginx/nginxconf.saved", "/etc/nginx/nginx.conf");
console.log("Restart yarn dev");
} else {
console.log(`ready to use http://${param.dns}`);
}
});
};
// check nginx exist // check nginx exist
if (!fs.existsSync("/etc/nginx/nginx.conf")) { if (!fs.existsSync("/etc/nginx/nginx.conf")) {
console.log( console.log(
@ -172,19 +53,12 @@ argv.slice(2).forEach((arg) => {
param[kv[0]] = kv[1]; param[kv[0]] = kv[1];
} }
}); });
if (
Object.keys(param).length > 0 &&
param.nationId &&
param.townId &&
param.dns
) {
setconf(param);
}
// setup_xx.json is gitignore so at first install we are in dev configuration // setup_xx.json is gitignore so at first install we are in dev configuration
let infotown = { let infotown = {
nationId: "ants", nationId: "ants",
townId: "devfarm", townId: "devfarm",
dns: ["devfarm-ants"], dns: "devfarm-ants",
comment: comment:
"Auto generate setup from apxtrib after node apxtrib nationId:value townId:value dns:domaine_to_access", "Auto generate setup from apxtrib after node apxtrib nationId:value townId:value dns:domaine_to_access",
}; };
@ -192,32 +66,42 @@ if (fs.existsSync(`${__dirname}/adminapi/www/adminapx/conf/setup_xx.json`)) {
infotown = fs.readJsonSync( infotown = fs.readJsonSync(
`${__dirname}/adminapi/www/adminapx/conf/setup_xx.json` `${__dirname}/adminapi/www/adminapx/conf/setup_xx.json`
); );
} else { };
fs.outputJsonSync( if (
`${__dirname}/adminapi/www/adminapx/conf/setup_xx.json`, Object.keys(param).length > 0 &&
infotown param.nationId &&
); param.townId &&
} param.dns
) {
infotown.nationId = param.nationId;
infotown.townId = param.townId;
infotown.dns = param.dns;
}
fs.outputJsonSync(
`${__dirname}/adminapi/www/adminapx/conf/setup_xx.json`,
infotown
);
infotown.dirapi=__dirname;
infotown.dirtown=path.resolve(`${__dirname}/../${infotown.townId}-${infotown.nationId}`);
process.env.dirtown=infotown.dirtown;
if ( if (
!fs.existsSync( !fs.existsSync(`${infotown.dirtown}/conf.json`) ||
path.resolve(
`${__dirname}/../${infotown.townId}-${infotown.nationId}/conf.json`
)
) ||
!fs.existsSync(`${__dirname}/adminapi/www/nginx_adminapx.conf`) !fs.existsSync(`${__dirname}/adminapi/www/nginx_adminapx.conf`)
) { ) {
// Case of new town or request a reset of dns to access adminapx // Case of new town or request a reset of dns to access adminapx
setconf(infotown); // genere a minimum conf with nationId, townId, dns, dirapi, dirtown
fs.outputJsonSync(`${infotown.dirtown}/conf.json`,infotown,{space:2});
const Towns = require('./api/models/Towns')
const rescreate = Towns.create();
if (rescreate.status!=200){
console.log('Sorry error ')
process.exit();
}
} }
const conf = require(path.resolve( const conf = require(`${infotown.dirtown}/conf.json`);
`${__dirname}/../${infotown.townId}-${infotown.nationId}/conf.json`
));
process.env.dirtown = conf.dirtown;
// Create and update ./nationchains // Create and update ./nationchains
const { updateobjectsfromfreshesttown } = require("./api/models/Nations.js"); const { updateobjectsfromfreshesttown } = require("./api/models/Nations.js");
updateobjectsfromfreshesttown(conf.towns, { updateobjectsfromfreshesttown(conf.towns, {
pagans: "alias_all.json", pagans: "alias_all.json",