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",
"description":"Nation date of creation",
"type": "string",
"format":"datetime"
"format":"date-time"
},
"contracts":{
"title":"Social contract of the nation",

View File

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

View File

@ -9,6 +9,7 @@
"mainlivinglocation":{"type":"object","$ref":"https://schema.org/PostalAddress"},
"secondlivinglocation":{"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"},
"skills":{"type":"array","$ref":"schema/skills.json"},
"educations":{"type":"array","$ref":"schema/educations.json"},

View File

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

View File

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

View File

@ -9,7 +9,7 @@ root {{{dirapi}}}/;
location ~* /nationchains/schema/ {
#outside of nationchains for git purpose
rewrite /nationchains/schema/(.*$) /$1 break;
root {{{dirapi}}}/adminapi/www/adminapx/schema/;
root {{{dirapi}}}/adminapi/schema/;
}
# /plugins/pluginame/components/xxx?plugin=pluginname&pluginkey=key
# 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">
<!-- 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/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
<link rel="stylesheet" href="static/style/apxobjmanager.css">
<script>
const apxlocal = {
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/apxtowns.js"></script>
<script src="static/js/apxapp.js"></script>
<script src="static/js/apxobjmanager.js"></script>
<style>
.fakeimg {
height: 200px;
@ -89,8 +92,9 @@
aria-expanded="false">Mayor's Town</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" add2data tpl="static/tpl/townowner_en.mustache"
onclick="app.load('apxmain','townowner',towns.loadtpldata())">Own this town</a></li>
<li><a class="dropdown-item" href="#">Manage Tribes</a></li>
onclick="app.load('apxmain','townowner',towns.loadtpldata('owner'))">Own this town</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>
<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
document.getElementById("generatekeys").classList.add("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");
};
@ -188,6 +188,12 @@ pagans.registerIdentity = async () => {
.post("api/pagans", data, { headers: apx.data.headers })
.then((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) => {
console.log("sorry", err);

View File

@ -4,26 +4,59 @@
"use strict";
var towns = towns || {};
towns.loadtpldata = () => {
towns.loadtpldata = (fortpl) => {
// adapte tpldata to template tpl
if (fortpl == "owner") {
const dataowner = apx.data.tpldata.setup;
dataowner.alias=apx.data.headers.xalias;
dataowner.auth = dataowner.alias!="anonymous";
dataowner.alias = apx.data.headers.xalias;
dataowner.auth = dataowner.alias != "anonymous";
dataowner.devtown = dataowner.townId == "devfarm";
if (dataowner.mayorid) dataowner.owner = dataowner.mayorid == dataowner.alias;
console.log('Data return to template',dataowner)
if (dataowner.mayorId)
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) => {
// only the owner can give ownership to someone else
if (!newowner) {newowner=apx.data.headers.xalias}
axios.get(`api/towns/changeowner/${newowner}`,{ headers: apx.data.headers }).then(rep=>{
console.log(rep)
apx.data.tpldata.setup.moyorId=newowner;
if (!newowner) {
newowner = apx.data.headers.xalias;
}
axios
.get(`api/towns/changeowner/${newowner}`, { headers: apx.data.headers })
.then((rep) => {
console.log(rep);
apx.data.tpldata.setup.mayorId = newowner;
apx.save();
app.load('apxmain','townowner',towns.loadtpldata())
}).catch(err=>{
console.log(err)
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>
<div class="input-group mb-3">
<input class="form-control me-1" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-primary" onclick="app.search(this)">
<i class="fa-solid fa-magnifying-glass"></i>
<button class="btn btn-outline-primary btn-sm" onclick="app.search(this)">
<i class="bi-search"></i>
</button>
</div>
<h4 class="mt-4">Articles</h4>

View File

@ -20,7 +20,7 @@
{{^mayorId}}
<p>
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}} 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}}
@ -30,13 +30,13 @@
{{#devtown}}
<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>
<p>Come back here.</p>
<p>Then Come back here.</p>
{{/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>
<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">
<button class="btn btn-outline-secondary" type="button" id="button-chgown">Give him the role on this town</button>
<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" onclick="towns.owntown(document.getelementbyId('newowner').value)">Give him the role on this town</button>
</div>
{{/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"))
req.params.xlang = req.header("Content-Language");
let missingheader = [];
console.log("req.headers", req.headers);
//console.log("req.headers", req.headers);
for (const h of conf.api.exposedHeaders) {
//console.log( h, req.header( h ) )
if (req.params[h]) {

View File

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

View File

@ -42,7 +42,7 @@ Nations.updateobjectsfromfreshesttown = (dnstownlist, objectidx) => {
objlist.forEach((o) => {
let objconf = {
name: o,
schema: `nationchains/schema/${o}.jsons`,
schema: `adminapi/schema/${o}.jsons`,
lastupdate: -1,
};
if (fs.existsSync(`${conf.dirapi}/nationchains/${o}/conf.json`)) {
@ -54,6 +54,7 @@ Nations.updateobjectsfromfreshesttown = (dnstownlist, objectidx) => {
});
//console.log(localversion);
for (let t = 0; t < dnstownlist.length; t++) {
if (conf.townId != dnstownlist[t].townId) { // to avoid update itself
let promiseconf = [];
let objecttotest = [];
objlist.forEach((o) => {
@ -111,6 +112,7 @@ Nations.updateobjectsfromfreshesttown = (dnstownlist, objectidx) => {
console.log(err);
});
}
}
};
Nations.synchronizeold = () => {
/*

View File

@ -2,6 +2,7 @@ const glob = require("glob");
const path = require("path");
const fs = require("fs-extra");
const dayjs = require("dayjs");
const axios = require("axios");
const conf = require(`${process.env.dirtown}/conf.json`);
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
@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
*/
const res = { status: 200 };
/* const res = { status: 200,ref="Odmdb",msg:"",data:{} };
//get schema link of object
const schemaPath = fs.readJsonSync(
`${objectPath}/${objectName}/idx/confjson`
`${objectPath}/${objectName}/idx/conf.json`
)["schema"];
if (schemaPath.substring(0, 4) == "http") {
// lance requete http pour recuperer le schema
} else {
schema == "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
res.data.schema = Odmdb.schema(objectPath, objectName, withschemacheck);
}
// check schema validity
const schema = Odmdb.schema(objectPath, objectName, withschemacheck);
if (schema.status != 200) return schema;
// check schema validity in case withschemacheck
if (schema.status != 200) return ;
console.log("SCHEMA for checking:");
console.log(schema.data);
console.log("DATA to check:");
@ -207,6 +207,43 @@ Odmdb.Checkjson = (objectPath, objectName, data, withschemacheck) => {
}
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) => {
/*
@search= {
@ -228,51 +265,78 @@ Odmdb.search = (objectPath, objectName, search) => {
};
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
@fieldList key to return for each object
Return objectName {status:200; data:{found:[{primarykey,field}],notfound:[uuid]}
if all primarykey exist then data.notfound does not exist
if all primarykey does not exist data.found does not exist
Return {status:200; data:{uuid:{data filter by @fieldList},uuid:"notfound"}}
*/
const res = { status: 200, data: {} };
uuidprimarykeyList.forEach((id) => {
if (fs.existsSync(`${objectPath}/${objectName}/${id}.json`)) {
if (!res.data.found) res.data.found = [];
uuidprimarykeyList.forEach(id => {
if (fs.existsSync(`${objectPath}/${objectName}/itm/${id}.json`)) {
const objectdata = fs.readJsonSync(
`${objectPath}/${objectName}/${id}.json`
`${objectPath}/${objectName}/itm/${id}.json`
);
if (!fieldList) {
res.data.found.push(objectdata);
res.data[id]=objectdata;
} else {
const objinfo = {};
fieldlList.forEach((k) => {
if (objectdata[k]) objinfo[k] = objectdata[k];
});
res.data.found.push(objinfo);
res.data[id]=objinfo;
}
} else {
if (!res.data.notfound) res.data.notfound = [];
res.data[id]="notfound";
}
});
return res;
};
Odmdb.create = (objectPath, objectName, data) => {
Odmdb.create = (objectPath, objectName, data, accessright) => {
/*
Create an objects data into objectName
@objectPath path to the folder that contain /objects/objectName/ /objectsInfo/objectName_lg.json /objectsMeta/objectName.json
@objectName name of object
@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 = async (objectPath, objectName, data, id, accessright) => {
/*
Create an objects data into objectName
@objectPath path to the folder that contain /objects/objectName/ /objectsInfo/objectName_lg.json /objectsMeta/objectName.json
@objectName name of object
@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.update = (objectPath, objectName, data) => {
/*
Create an objects data into objectName
@objectPath path to the folder that contain /objects/objectName/ /objectsInfo/objectName_lg.json /objectsMeta/objectName.json
@objectName name of object
@data data to check based on objectsMeta definition
*/
};
Odmdb.delete = (objectPath, objectName, data) => {
Odmdb.delete = (objectPath, objectName, data,accessright) => {
/*
Create an objects data into objectName
@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
) {
// 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 {
// replace itm with data
localidx[id] = data[id];

View File

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

View File

@ -6,9 +6,141 @@ const jwt = require("jwt-simple");
const UUID = require("uuid");
const conf = require(`${process.env.dirtown}/conf.json`);
const Checkjson = require(`./Checkjson.js`);
const Odmdb = require("./Odmdb.js");
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) => {
/**
*
*/
@ -22,15 +154,46 @@ Towns.changeowner = (newowner, requestby) => {
}
if (!conf.mayorId || conf.mayorId == requestby) {
// 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;
fs.outputJsonSync(`${process.env.dirtown}/conf.json`, conf);
const setup = fs.readJSONSync(`${dirapi}/adminapi/www/adminapx/conf/setup_xx.json`)
setup.mayorId=newowner;
fs.outputJsonSync(`${dirapi}/adminapi/www/adminapx/conf/setup_xx.json`,setup);
const setup = fs.readJSONSync(
`${conf.dirapi}/adminapi/www/adminapx/conf/setup_xx.json`
);
conf.mayorId = newowner;
//update the setup file for webapp adminapi
fs.outputJsonSync(
`${conf.dirapi}/adminapi/www/adminapx/conf/setup_xx.json`,
setup
);
return {
status: 200,
ref: "towns",
msg: "newownerchangesusccess",
msg: "newownerchangesuccess",
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)
* 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 newpagan = Pagans.create(req.body.alias, req.body.publickey);
if (newpagan.status == 200) {
@ -136,20 +136,29 @@ router.post("/", checkHeaders, isAuthenticated, (req, res) => {
if (req.app.locals.tribeids.includes(req.body.trustedtribe)) {
delete feedback.withemail;
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)
);
);*/
} else {
res.send({
status: 404,
res.status(404).json({
status:404,
ref: "Pagans",
msg: "tribedoesnotexist",
data: { tribe: req.body.trustedtribe },
});
/*res.send({
status: 404,
ref: "Pagans",
msg: "tribedoesnotexist",
data: { tribe: req.body.trustedtribe },
});*/
}
} else {
newpagan.data = feedback;
res.send(newpagan);
res.status(newpagan.status).json(newpagan);
//res.send(newpagan);
}
} else {
//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
* @todo add tribe/schema/person.json
*/
console.log(req.body);
res.send(
Pagans.personupdate(req.body.alias, req.session.header.xtribe, req.body)
);
//console.log(req.body);
const persoup = Pagans.personupdate(req.body.alias, req.session.header.xtribe, req.body);
res.status(persoup.status).json(persoup);
});
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} }
*
**/
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) => {
/**
* @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 ...
*/
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
if (!fs.existsSync("/etc/nginx/nginx.conf")) {
console.log(
@ -172,19 +53,12 @@ argv.slice(2).forEach((arg) => {
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
let infotown = {
nationId: "ants",
townId: "devfarm",
dns: ["devfarm-ants"],
dns: "devfarm-ants",
comment:
"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(
`${__dirname}/adminapi/www/adminapx/conf/setup_xx.json`
);
} else {
fs.outputJsonSync(
};
if (
Object.keys(param).length > 0 &&
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 (
!fs.existsSync(
path.resolve(
`${__dirname}/../${infotown.townId}-${infotown.nationId}/conf.json`
)
) ||
!fs.existsSync(`${infotown.dirtown}/conf.json`) ||
!fs.existsSync(`${__dirname}/adminapi/www/nginx_adminapx.conf`)
) {
// 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(
`${__dirname}/../${infotown.townId}-${infotown.nationId}/conf.json`
));
process.env.dirtown = conf.dirtown;
const conf = require(`${infotown.dirtown}/conf.json`);
// Create and update ./nationchains
const { updateobjectsfromfreshesttown } = require("./api/models/Nations.js");
updateobjectsfromfreshesttown(conf.towns, {
pagans: "alias_all.json",