This commit is contained in:
2023-11-19 16:34:37 +01:00
parent 6291d5239e
commit e9c95d5c50
45 changed files with 4035 additions and 353 deletions

View File

@@ -1,23 +1,21 @@
const conf = require(`${process.env.dirtown}/conf.json`);
const checkHeaders = (req, res, next) => {
/**
* @apiDefine apxHeader
* @apiGroup Middleware
* @apiDescription Header is mandatory to access apxtrib see tribes/townconf.json.exposedHeaders
* A turn around can be done with a simple get params has to be sent in the get url. Usefull to send simple get without header like ?xworkon=tribeName&xlang=en... priority is given to headers
* For performance, tokens are store globaly in req.app.locals.tokens={xpaganid:xauth}
* if xlang is not in conf.languagesAvailable
* @api{get}/CheckHeaders
* @apiGroup Middlewares
* @apiName CheckHeaders
* @apiDescription a list of header is mandatory to access apxtrib see tribes/townconf.json.exposedHeaders
*
* @apiHeader {string} xjwt Pagans unique jwt token store in local town Pagans data or "noauth"
* @apiHeader {string} xpseudo Pagans unique Pagan id in uuid format or "nouuid"
* @apiHeader {string} xlang the 2 letter langage it request the api (if not exist the 2 first letter of Accept-Language header ) if lang does not exist in the town then en is set (as it always exist in en).
* @apiHeader {string} xtribe Tribes id where pseudo want to act
* @apiHeader {string} xapp Name of www/xapp folder that host app that send the request
* /tribeid/person/xpseudo.json have accessright on this app store in /tribe/tribeid/www/xapp
* @apiHeader {string} xalias anonymous or unique alias
* @apiHeader {string} xapp name of the webapp store in tribe/tribeid/www/xapp
* @apiHeader {string} xlang the 2 letter request langage (if does not exist then return en = english).
* @apiHeader {string} xtribe unique tribe name ere xapp exist
* @apiHeader {string} xdays a timestamp 0 or generate during the authentifyme process
* @apiHeader {string} xhash anonymous or signature of message: xalias_xdays created by alias private key during authentifyme process
* @apiHeader {array[]} xprofils list of string profil apply into xtribe for xapp
* @apiHeader {string} xuuid a unique number c reated the fisrt time a domain is visited
* @apiHeader {integer} xtrkversion a version number link to tracking system
*
* @apiError missingexposedHeaders it miss an exposedHeaders
*
* @apiErrorExample {json} Error-Response:
* HTTP/1/1 400 Not Found
* {
@@ -34,7 +32,6 @@ const checkHeaders = (req, res, next) => {
* msg:"tribeiddoesnotexist",
* data: {xalias}
* }
*
* @apiHeaderExample {json} Header-Exemple:
* {
* xtribe:"apache",
@@ -45,6 +42,7 @@ const checkHeaders = (req, res, next) => {
* xapp:"popular"
* }
*/
const checkHeaders = (req, res, next) => {
req.session = {};
const header = {};
if (!req.header("xlang") && req.header("Content-Language"))

View File

@@ -0,0 +1 @@
Documentation Best practices

148
api/middlewares/header.md Normal file
View File

@@ -0,0 +1,148 @@
## api users and backend developers
api documentation for routes and middleware has to respect apidoc's rules [https://apidocjs.com/](https://apidocjs.com) 
To update this doc accessible in [https://wal-ants.ndda.fr/cdn/apidoc](https://wal-ants.ndda.fr/cdn/apidoc) :
`yarn apidoc` 
For api tribe's doc  accessible in [https://smatchit.io/cdn/apidoc](https://smatchit.io/cdn/apidoc) [:](https://smatchit.io/cdn/apidoc:) 
`yarn apidoctribename`
Objects manage in apXtrib: pagans, notifications, nations, towns, tribes, wwws 
All others objects are manage in town/tribe 
persons is the only exception, schema is manage in apXtrib but data are store in a tribe.
apxtrib conf is set in a conf.json at the same folder level:
```plaintext
/apxtrib/ # core process
/townName_nationName/conf.json # town settings
```
url: **/api/routeName** For core api apXtrib in /apxtrib :
```plaintext
/apxtrib/api/middlewares/
/apxtrib/api/routes/
/apxtrib/api/models/
/apxtrib/api/models/lg/ language customisation for api response
/apxtrib/api/models/unitest/
```
url: **/api/smatchit/routeName** for tribe smatchit example api in /town\_nation/tribes/smatchit(tribeid) 
```plaintext
/town_nation/tribes/smatchit/api/routes/
/town_nation/tribes/smatchit/api/models/
/town_nation/tribes/smatchit/api/models/lg/ language customization
```
**static files** are served by nginx, each tribe nginx conf are store and can be customize in /town\_nation/www/nginx\_xtribe\_xapp.conf
object www/websitename are serve with nginx not express.
## Object management (Odmdb)
An object has a name and is defined by a schema that contain properties key.
A propertie has a name and a list of caracteristics (type, pattern,format,...) that have to be validate to be accepted.
All properties respect the rules [https://json-schema.org/draft/2020-12/schema,](https://json-schema.org/draft/2020-12/schema,) some extra"format" can be add to mutualise recurrent regex pattern
A checkjson.js is available to manage all specific format [https://wall-ants.ndda.fr/Checkjson.js](https://wall-ants.ndda.fr/Checkjson.js) see **Odmdb - schema Checkjson**
**Additional properties that not exist in 2020-12/schema :**
**required**: an array of required properties
**apxid**: the propertie used as an unique id
**apxuniquekey**: array of unique properties
**apxidx** : array of index
**apxaccessrights**: object with key profilname and accessrights on properties {profilname:{C:\[properties array\],R:\[properties array\],U:\[\],D:\[\]}}
Items of an object are store in files into :  
```plaintext
/objectnames/idx/keyval_objkey.json
/objectnames/itm/uniqueid.json
```
## api pre-request
**Valid header**
A private request to pass must contain exposeHeaders from town conf.json
api.exposedHeaders :\["xdays", "xhash", "xalias", "xlang", "xtribe", "xapp", "xuuid" \]
By default for anonymous user:
```plaintext
{"headers":{
"xtrkversion":1,
"xtribe":"tribeid ex: smatchit",
"xapp":"websitename ex:presentation",
"xlang":"fr",
"xalias":"anonymous",
"xhash":"anonymous",
"xdays":0
}
}
```
App use openpgp.js lib to sign xdays\_xalias with a privatekey and store it in xhash.
/api/middlewares/isAuthenticated.js check if (xhash) is a valid signature of the public key a xhash is valid for 24 hours
See Pagans models that contain authentification process
**api Return can be direct json in case of get without authenntification or an object data**
{status, ref,msg,data}:
* status: http code return
* ref: model/route name reference where message come from
* msg: a message template key store into models/lg/name\_lg.json (where lg is 2 letters language)
* data: an object data use to render the value of the message key.
## Accessrights:
An alias is just an identity, to access a tribe a person must exist with alias into /town/tribes/tribename/persons/itm/alias.json
A person has a property profils with a list of profilename, common profiles are : pagan (an identity)  / person (an identity with access right in a tribe) / druid (the administrator of a tribe) / major (administrator of a town/server)
Into a tribe you can have many other profil with specifics accessright on tribe's object.
## Add tribe's api:
Accessible with https://dns/api/tribename/routes
```plaintext
/town/tribes/tribename/api/routes
/town/tribes/tribename/api/middlewares
/town/tribes/tribename/api/models
/town/tribes/tribename/schema
/town/tribes/tribename/schema/lg
```
```plaintext
// Example of a route
const conf = require(`${process.env.dirtown}/conf.json`);
const express = require(`${conf.dirapi}/node_modules/express`);
const fs = require(`${conf.dirapi}/node_modules/fs-extra`);
const path = require(`${conf.dirapi}/node_modules/path`);
const Nofications = require(`${conf.dirapi}/api/models/Notifications.js`);
// Middlewares
const checkHeaders = require(`${conf.dirapi}/api/middlewares/checkHeaders`);
const isAuthenticated = require(`${conf.dirapi}/api/middlewares/isAuthenticated`);
const Actions = require(`${conf.dirtown}/tribes/smatchit/api/models/Actions`);
const router = express.Router();
```

View File

@@ -6,24 +6,51 @@ const glob = require("glob");
const openpgp = require("openpgp");
/**
* Check authentification and get person profils for a tribe
* @param {object} req
* @param {object} res
* @param {function} next
* @returns {status:}
* @api{get}/istauthenticated
* @apiGroup Middlewares
* @apiName isAUthenticated
* @apiDescription Check that exist in town/tmp/tokens/xalias_xdays_xhash.substr(20,200) if not, check the xhash signature with message xalias_xdays come from public key belonging to xalias. If check pass then store a xhash into /tmp/tokens.
* A process run each day to clean up all xhas tmp/tokens oldest than 24 hours.
* If authentify it returns header with xprofils store into a person objject -xtribes/person/alias
*
* 3 steps:
* - clean eventual tokens oldest than 24 hours (the first pagan that authenticate of the day will process this)
* - if token present in /town/tmp/tokens/alias_tribe_part of the xhash return xprofils with list of profils pagans
* - if no token then check xhash with openpgp lib and create one
* @apiHeader {string} xalias anonymous or unique alias
* @apiHeader {string} xapp name of the webapp store in tribe/tribeid/www/xapp
* @apiHeader {string} xlang the 2 letter request langage (if does not exist then return en = english).
* @apiHeader {string} xtribe unique tribe name ere xapp exist
* @apiHeader {string} xdays a timestamp 0 or generate during the authentifyme process
* @apiHeader {string} xhash anonymous or signature of message: xalias_xdays created by alias private key during authentifyme process
* @apiHeader {array[]} xprofils list of string profil apply into xtribe for xapp
* @apiHeader {string} xuuid a unique number c reated the fisrt time a domain is visited
* @apiHeader {integer} xtrkversion a version number link to tracking system
*
* All data related are store in town/tmp/tokens backend, and localstorage headers for front end
* A penalty function increase a sleep function between 2 fail try of authentification to avoid bruteforce
*/
* @apiErrorExample {json} Error-Response:
* HTTP/1/1 400 Not Found
* {
* status:400,
* ref:"middlewares"
* msg:"missingheaders",
* data: ["headermissing1"]
* }
*@apiErrorExample {json} Error-Response:
* HTTP/1/1 404 Not Found
* {
* status:404,
* ref:"middlewares"
* msg:"tribeiddoesnotexist",
* data: {xalias}
* }
*
* @apiHeaderExample {json} Header-Exemple:
* {
* xtribe:"apache",
* xalias:"toto",
* xhash:"",
* xdays:"123"
* xlang:"en",
* xapp:"popular"
* }
**/
const isAuthenticated = async (req, res, next) => {
// tokens if valid are store in /dirtown/tmp/tokens/xalias_xdays_xhash(20,200)
// once a day rm oldest tokens than 24hours tag job by adding tmp/tokensmenagedone{day}
const withlog = true;
const currentday = dayjs().date();
fs.ensureDirSync(`${process.env.dirtown}/tmp/tokens`);
@@ -78,11 +105,6 @@ const isAuthenticated = async (req, res, next) => {
150 + tmpfs.length - 249
)}.json`;
/**
*
* @param {string} alias that request an access
* @param {string} action "clean" | "penalty"
*/
const bruteforcepenalty = async (alias, action) => {
const sleep = (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms));

View File

@@ -1,7 +1,7 @@
/*
This module have to be use in back as well front
can be include in project with
- into a browser : <script src="https://townName.nationName.dns/nationchains/contracts/Checkjson.js"></script>
- >into a browser : <script src="https://townName.nationName.dns/nationchains/contracts/Checkjson.js"></script>
- into a node.js : const Checkjson = require( `../nationchains/socialworld/contracts/Checkjson.js`);
*/
// --##

View File

@@ -352,10 +352,13 @@ Odmdb.cud = (objectPathname, crud, itm, role) => {
data: { missingkey: getschema.data.schema.apxid },
};
}
const pathindex=`${objectPathname}/idx/lst_${getschema.data.schema.apxid}.json`;
if (!fs.existsSync(pathindex)){
fs.outputJSONSync(pathindex,[])
fs.ensureDirSync(`${objectPathname}/itm/`);
}
const existid = fs
.readJSONSync(
`${objectPathname}/idx/lst_${getschema.data.schema.apxid}.json`
)
.readJSONSync(pathindex)
.includes(itm[getschema.data.schema.apxid]);
if (existid && crud == "C") {
return {
@@ -392,7 +395,7 @@ Odmdb.cud = (objectPathname, crud, itm, role) => {
// set owner cause this is a Create
itm.owner = role.xalias;
}
//get accessrigh {C:[],R:[],U:[],D:[]} if exist means authorize, if array contain properties (for R and U) right is only allowed on properties
//get accessright {C:[],R:[],U:[],D:[]} if exist means authorize, if array contain properties (for R and U) right is only allowed on properties
const accessright = Odmdb.accessright(
getschema.data.schema.apxaccessrights,
role

View File

@@ -1,57 +1,29 @@
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`);
const Trackings = {}
/**
* Tracking management:
*
* without header:
* https://dns.xx/trk/pathtofile?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&src=btnregister&version=1&lg=fr
* Tracking system management
*
* with header
* https://dns.xx/trk/pathtofile?src=btnregister&version=1
*
* where pathtofile is a ressource accessible from https://dns.xx/pathtofile
*
* We get :
* alias: if athenticated from header else anonymous
* uuid: a uuid v4 générate the first time a web page is open on a browser
* src: source action that trig this get
* version: can be an int, date or any version of the src
* tm: optionnal is a timestamp of action when it is not immediate (offline app)
*
* html usage to track a loading page or email when a picture is load
* using apxwebapp in /src/ we got:
* <img src="static/img/photo.jpg" data-trksrckey="loadpage" data-version="1">
*
* using html + apx.js (or at least with header {xalias,xuuid,xlang})
* <img lazysrc="trk/static/img/photo.jpg data-trksrckey="loadpage" data-version="1">
*
*
* in js action:
* <button></button> or
* <a data-trksrc="linktoblabla" href='https:..'
* onclick="apx.trackvisit("btnaction",1);actionfct();">
* </a>
* will hit an eventlistener
* axios.get("https://dns.xx/trk/cdn/empty.json?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&src=btnregister&version=1");
*
*
* or if no js available (example:email or pdf document)
* <img src="https://dns.xx/trk/static/img/photo.jpg?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&srckey=loadpage&version=1" will hit a tracker
*
* <a href="https://dns.xx/trk/redirect?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&srckey=loadpage&version=1&url=http://..." will hit a tracker then redirect to url></a> *
*
*
* if you use apx.js :
* in html add in <button>, <img>, <a> tag data-trksrc="srckey"
* <img src="https://dns.xx/static/img/photo.jpg" data-trkversion="1" data-trksrckey="registerform">
* <button data-trksrc="https://dns.xx/static/img/photo.jpg" data-trkversion="1" data-trksrckey="registerform">
* in js call apx.track(srckey);
*
* Tracking log into tribe/logs/nginx/tribe_appname.trk.log
* Src have to be manage in tribe/api/models/lg/src_en.json
* {"srckey":{
* "app":"presentation|app|apptest",
* "title":"",
* "description":""
* }
* }
*
*/
* Data collection is done from nginx log system see routes/trackings.js for doc
*/
/**
* Process plan to run each night or on demand to collect log data and cleanup
*/
Trackings.logcollection=()=>{
}
Trackings.dashboard=(graphname)=>{
console.log('Process data to provide a specific graph')
}
module.export = Trackings;

View File

@@ -4,10 +4,11 @@
"getschema": "Schema {{{conf.name}}}",
"schemanotfound": "Schema introuvable dans {{{schemaPath}}}",
"pathnamedoesnotexist": "Le repertoire n'existe pas {{{indexpath}}}",
"objectfiledoesnotexist": "Le fichier n'exuiste pas {{{objectpath}}}",
"objectfiledoesnotexist": "Le fichier n'existe pas {{{objectpath}}}",
"cudsuccessfull": "Mise à jour effectuée avec succés",
"misssingprimarykey": "Il manque une clé primaire apxid pour stocker et identifier les objects",
"missingprimarykey": "Il manque une clé primaire apxid pour stocker et identifier les objects",
"unconsistencyapxidx": "L'index {{name}} doit contenir en objkey au moins {{apxid}} car keyval n'est pas unique",
"profilnotallow": "Vous n'avez pas le profil de {{profils}}, cette action n'est pas authorisée",
"successreindex": "Objet reindexé à partir des items, vos index sont à jour"
"successreindex": "Objet reindexé à partir des items, vos index sont à jour",
"indexexist":"L'indexe existe"
}

View File

@@ -0,0 +1,59 @@
const express = require("express");
const fs = require("fs-extra");
const path = require("path");
// Classes
const Pagans = require("../models/Notifications.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const router = express.Router();
/**
* Get form data and send notification to user by email, sms, alert
* @api{post}/messageanonymous
* @apiName Notification
* @apiDescription Send information as anonymous to tribe's druid
* @apiGroup apxtrib
*
* @apiUse apxHeader
* @apiParam {string} objectname Mandatory
* @apiParam {String} indexname Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname/idx/indexname indexname contains the ObjectName .*_ (before the first _)
*
*
* @apiError {json} objectNotfound the file does not exist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
{"status":404,"ref":"Odmdb","msg":"pathnamedoesnotexist","data":{indexpath}}
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"indexexist", "data":{indexname,content:{index file}}
*
*
**/
router.get("/alias/:alias", (req, res) => {
const getalias = Pagans.getalias(req.params.alias);
res.status(getalias.status).send(getalias);
});
/**
* Remove serveur token
* @api {get} /pagans/logout
* @apiName Remove token
* @apiGroup Pagans
*
*/
router.get("/logout", checkHeaders, isAuthenticated, (req, res) => {
console.log(req.session.header);
const logout = Pagans.logout(
req.session.header.xalias,
req.session.header.xtribe,
req.session.header.xdays,
req.session.header.xhash
);
res.status(logout.status).json(logout);
});
module.exports=router;

View File

@@ -9,162 +9,166 @@ const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const router = express.Router();
/**
* @api {get} /odmdb/rebuildidx/:objectname
* @apiName Rebuild all index for an object
/**
* @api{get}/odmdb/idx/:objectname/:indexname - index Get
* @apiGroup Odmdb
* @apiName getIndex
* @apiDescription Get index file for an object
*
* @apiUse apxHeader
* @objectname {string} Mandatory
* @apiParam {string} objectname If in conf.nationObjects then object is into nationchains/ else in tribes/xtribe/objectname/idx/indexname indexname
* @apiParam {String} indexname name of index file in /idx/indexnamme.json
*
* @apiError (404) {string} status the file does not exist
* @apiError (404) {string} ref objectmodel to get in the right language
* @apiError (404) {string} msg key to get template from objectmodel
* @apiError (404) {object} data use to render lg/objectmodel_lg.json
*
* @apiError {json} objectNotfound the file does not exist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
{"status":404,"ref":"Odmdb","msg":"pathnamedoesnotexist","data":{indexpath}}
*
* @apiSuccess (200) {object} data contains indexfile requested
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"indexexist", "data":{indexname,content:{index file}}
*
*
*/
router.get(
"/rebuildidx/:objectname",
checkHeaders,
isAuthenticated,
(req, res) => {
console.log("reindex");
// check validity and accessright
const objectPathname = conf.api.nationObjects.includes(
req.params.objectname
)
? `${conf.dirapi}/nationchains/${req.params.objectname}`
: `${conf.dirtown}/tribes/${req.session.header.xtribe}/${req.params.objectname}`;
//console.log(objectPathname);
if (!fs.existsSync(objectPathname)) {
res.status(404).json({
status: 404,
ref: "Odmdb",
msg: "pathnamedoesnotexist",
data: { indexpath: objectPathname },
});
return false;
router.get(
"/idx/:objectname/:indexname",
checkHeaders,
isAuthenticated,
(req, res) => {
console.log("passe");
// indexname = objectname_key_value.json
let objectLocation = "../../nationchains/";
if (!conf.api.nationObjects.includes(req.params.objectname)) {
objectLocation += `tribes/${req.session.headers.xtribe}/`;
// check if accessright
}
const indexpath = `${objectLocation}/${req.params.objectname}/idx/${req.params.indexname}`;
if (fs.existsSync(indexpath)) {
res
.status(200)
.json({
ref: "Odmdb",
msg: "indexexist",
data: {
indexname: req.params.indexname,
content: fs.readJsonSync(indexpath),
},
});
} else {
res.status(404).json({
ref: "Odmdb",
msg: "pathnamedoesnotexist",
data: { indexpath },
});
}
}
if (
conf.api.nationObjects.includes(req.params.objectname) &&
!req.session.header.xprofils.includes("mayor")
) {
res.status(403).json({
status: 403,
ref: "Odmdb",
msg: "profilnotallow",
data: { profils: "mayor" },
});
return false;
}
if (
!conf.api.nationObjects.includes(req.params.objectname) &&
!req.session.header.xprofils.includes("druid")
) {
res.status(403).json({
status: 403,
ref: "Odmdb",
msg: "profilnotallow",
data: { profils: "druid" },
});
return false;
}
const reindex = Odmdb.idxfromitm(objectPathname, "I", {}, {}, [], {});
res.status(reindex.status).json(reindex);
}
);
);
/**
* @api {get} /odmdb/idx/:indexname
* @apiName Get index file for an object
* @api {get} /odmdb/rebuildidx/:objectname - index refresh all
* @apiGroup Odmdb
* @apiName refreshAllIndex
* @apiDescription Rebuild all index for an object, this can be usefull in case crash or any data conflict.
*
* @apiUse apxHeader
* @objectname {string} Mandatory
* @apiParam {String} indexname Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname/idx/indexname indexname contains the ObjectName .*_ (before the first _)
* @apiParam {string} objectname Mandatory
*
* @apiError (404) {string} status the file does not exist
* @apiError (404) {string} ref objectmodel to get in the right language
* @apiError (404) {string} msg key to get template from objectmodel
* @apiError (404) {object} data use to render lg/objectmodel_lg.json
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"successreindex", "data":{"indexlist":[]}}
*
* @apiSuccess (200) {object} data contains indexfile requested
* @apiError {json} objectNotfound the file does not exist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
{"status":404,"ref":"Odmdb","msg":"see nationchains/model/lg/Odmdb_xx.json","data":"object to render with msg"}
*
*/
router.get(
"/:objectname/idx/:indexname",
checkHeaders,
isAuthenticated,
(req, res) => {
console.log("passe");
// indexname = objectname_key_value.json
let objectLocation = "../../nationchains/";
if (!conf.api.nationObjects.includes(req.params.objectname)) {
objectLocation += `tribes/${req.session.headers.xtribe}/`;
// check if accessright
router.get(
"/rebuildidx/:objectname",
checkHeaders,
isAuthenticated,
(req, res) => {
console.log("reindex");
// check validity and accessright
const objectPathname = conf.api.nationObjects.includes(
req.params.objectname
)
? `${conf.dirapi}/nationchains/${req.params.objectname}`
: `${conf.dirtown}/tribes/${req.session.header.xtribe}/${req.params.objectname}`;
//console.log(objectPathname);
if (!fs.existsSync(objectPathname)) {
res.status(404).json({
status: 404,
ref: "Odmdb",
msg: "pathnamedoesnotexist",
data: { indexpath: objectPathname },
});
return false;
}
if (
conf.api.nationObjects.includes(req.params.objectname) &&
!req.session.header.xprofils.includes("mayor")
) {
res.status(403).json({
status: 403,
ref: "Odmdb",
msg: "profilnotallow",
data: { profils: "mayor" },
});
return false;
}
if (
!conf.api.nationObjects.includes(req.params.objectname) &&
!req.session.header.xprofils.includes("druid")
) {
res.status(403).json({
status: 403,
ref: "Odmdb",
msg: "profilnotallow",
data: { profils: "druid" },
});
return false;
}
const reindex = Odmdb.idxfromitm(objectPathname, "I", {}, {}, [], {});
res.status(reindex.status).json(reindex);
}
const indexpath = `${objectLocation}/${req.params.objectname}/idx/${req.params.indexname}`;
if (fs.existsSync(indexpath)) {
res.status(200).json({ data: fs.readJsonSync(indexpath) });
} else {
res.status(404).json({
ref: "Odmdb",
msg: "objectfiledoesnotexist",
data: { indexpath },
});
}
}
);
);
/**
* @api {get} /odmdb/itm/:objectname/:primaryindex
* @apiName Get index file for an object
* @api {post} /odmdb/itm/:objectname - item Create
* @apiGroup Odmdb
*
* @apiUse apxHeader
*
* @apiParam {String} objectname name Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname
* @apiParam {String} primaryindex the unique id where item is store
* @apiError (404) {string} status the file does not exist
* @apiError (404) {string} ref objectmodel to get in the right language
* @apiError (404) {string} msg key to get template from objectmodel
* @apiError (404) {object} data use to render lg/objectmodel_lg.json
*
* @apiSuccess (200) {object} data contains indexfile requested
* @apiName postItm
* @apiPermission none
* @apiDescription Add an new item (data) into a collection of objectname items. Before Check data integrity with the relevant schema.
* Then create a new primarykey. For multilanguage return see nationchains/model/lg/Odmdb_xx.json.
*
* @apiParam {string} objectname Place where to create new item, schema and version are available in /objectname/conf.json
*
* @apiBody {Object} data must pass Checkjson.js with schema
*
* @apiSuccess {json} data idxprimary Value of idxprimary into objectname collection
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"cudsuccessfull", "data":{"itm":{}}}
*
* @apiError {json} schemanotfound The objectname schema is not found
* @apiError {json} pathnamedoesnotexist The objectname does not exist for the tribe
* @apiError {json} missingprimarykey Body data must have primarykey to be created
* @apiError {json} unconsistencyapxidx some Body data get unique key that already exist
* @apiError {json} checkjsonfalse The body data are not consistent with the schema
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
* {"status":404,"ref":"Odmdb","msg":"see nationchains/model/lg/Odmdb_xx.json","data":"object to render with msg"}
*
*/
// indexname = objectname_key_value.json
router.get(
"/:objectname/itm/:primaryindex",
checkHeaders,
isAuthenticated,
(req, res) => {
const objectName = req.params.objectname;
const objectId = req.params.primaryindex;
let objectLocation = "../../nationchains/";
if (!conf.api.nationObjects.includes(objectName)) {
objectLocation += `tribes/${req.session.headers.xtribe}/${objectName}`;
// check if accessright on object on item
// in case not res.status(403)
}
const objectpath = `${objectLocation}/${objectName}/itm/${objectId}`;
if (fs.existsSync(objectpath)) {
res.status(200).json({ data: fs.readJsonSync(objectpath) });
} else {
res.status(404).json({
ref: "Odmdb",
msg: "objectfiledoesnotexist",
data: { objectpath },
});
}
}
);
router.post(":objectname/itm", checkHeaders, isAuthenticated, (req, res) => {
router.post("/itm/:objectname", checkHeaders, isAuthenticated, (req, res) => {
// Create an item of an object with no specificities
// if specificities then create a route / model that import odmdb
res.json({})
});
router.get(
"/searchitems/:objectname/:question",
@@ -194,22 +198,156 @@ router.get(
);
/**
* @api {get} /odmdb/schema/:objectname
* @apiName GetSchema
* @api {get} /odmdb/itm/:objectname/:primaryindex - item Get
* @apiGroup Odmdb
* @apiName getItemFromId
* @apiDescription Get itm for a primaryid of an object
*
* @apiUse apxHeader
* @apiParam {String} objectname name Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname
* @apiParam {String} primaryindex the unique id where item is store
*
* @apiParam {String} objectname Mandatory if headers.xworkon == nationchains then into ./nationchains/ else into ./tribes/xworkon/
* @apiError {json} objectNotfound the file item does not exist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
* {"status":404,"ref":"Odmdb","msg":"doesnotexist","data":{"objectname":"objectname","key":"apxid","val":"primaryindex"}}
*
* @apiError (404) {string} status a key word to understand not found schema
* @apiError (404) {string} ref objectmodel to get in the right language
* @apiError (404) {string} msg key to get template from objectmodel
* @apiError (404) {object} data use to render lg/objectmodel_lg.json
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"indexexist", "data":{"indexname","content":{itm file}}
*
* @apiSuccess (200) {object} data contains schema requested
*
*/
// indexname = objectname_key_value.json
router.get(
"/itm/:objectname/:primaryindex",
checkHeaders,
isAuthenticated,
(req, res) => {
const objectName = req.params.objectname;
const objectId = req.params.primaryindex;
let objectLocation = "../../nationchains/";
if (!conf.api.nationObjects.includes(objectName)) {
objectLocation += `tribes/${req.session.headers.xtribe}/${objectName}`;
// check if accessright on object on item
// in case not res.status(403)
}
const objectpath = `${objectLocation}/${objectName}/itm/${objectId}`;
if (fs.existsSync(objectpath)) {
res.status(200).json({ data: fs.readJsonSync(objectpath) });
} else {
res.status(404).json({
ref: "Odmdb",
msg: "objectfiledoesnotexist",
data: { objectpath },
});
}
}
);
/**
* @api {get} https://wall-ants.ndda.fr/Checkjson.js - schema check data lib
* @apiGroup Odmdb
* @apiName checkjsonjs
* @apiDescription Public js lib to import in a browser by :<br>
* ```<script src="wall-ants.ndda.fr/nationchains/contracts/Checkjson.js"></script>```
* to import in a node.js:<br>
* ```const Checkjson = require(`Checkjson.js`);```
*
* with functions:<br>
* <strong>Checkjson.schema.validation(schema)</strong> that return<br>
* - {status:200, ref:"Checkjson", msg:"validcheck"} => all rules are correct<br>
* - {status:406, multimsg:[{ref:"Checkjson",msg:"errorkey",data:{}}]}<br>
*
* <strong>Checkjson.schema.data(schema{json},data{json},withschemacheck{boolean})</strong> that return<br>
* - {status:200, ref:"Checkjson", msg:"validcheck"} => all data keys respect schema rules <br>
* - {status:417, multimsg:[{ref:"Checkjson",msg:"errorkey",data:{}}]}<br>
*
* To identify issues, get the language errorkey list with a get
* https://wall-ants.ndda.fr/nationchains/models/Checkjson_lg.json
*
*/
/**
* @api {get} https://wall-ants.ndda.fr/nationchains/schema/:objectname - schema Get public
* @apiGroup Odmdb
* @apiName getPublicSchema
* @apiDescription Get a Schema model from public apxtrib (nations, pagans,persons,towns, tribes,wwws)
* @apiSuccess {json} contain json file
* @apiSuccessExample {json} Fichier direct
* HTTP/1.1 200 Success-response:
{
"$id": "https://smatchit.io/schema/pagan",
"$comment": "To create account bin apxtrib",
"title": "Pagans identity",
"description": "A numeric id in the nationchains world",
"type": "object",
"properties": {
"publickey": {
"title": "Alias's publickey",
"description": "Public key generate with openpgp.js",
"type": "string",
"format": "pgppublickey"
},
"alias": {
"title": "Alias",
"description": "text to remember easily a public key",
"type": "string",
"minLength": 4,
"pattern": "^[a-z0-9]*$"
},
"dt_delete": {
"title": "Date of death",
"description": "Date of alias delete request, your will will be apply",
"type": "string",
"format": "date-time"
},
"will": {
"title": "Will script after death",
"description": "This will script will be apply on your data 30 days after your death",
"type": "string"
}
},
"required": ["publickey", "alias"],
"apxid": "alias",
"apxuniquekey": ["publickey"],
"apxidx": [
{ "name": "lst_alias", "keyval": "alias" },
{ "name": "alias", "keyval": "alias" }
],
"apxaccessrights": {
"owner": { "R": [], "D": [] },
"anonymous": { "C": [], "R": ["alias"] },
"pagan": { "R": ["alias", "publickey"] }
}
}
* @apiError {json} contain json file
* @apiErrorExample {string} nginx html not found message
* HTTP/1.1 404 Not Found
* <html>...</html>
**/
/**
* @api {get} /odmdb/schema/:objectname - schema Get private
* @apiGroup Odmdb
* @apiName getPrivateSchema
* @apiDescription Get a private (profil must have accessright R on object) to a Schema model
*
* @apiParam {String} objectname Mandatory
*
* @apiError {object} ref objectmodel to get in the right language
* @apiErrorExample {json} Error-response:
* HTTP/1.1 404 Not Found
* {"status":404,"ref":"Odmdb","msg":"schemanotfound","data":{"fullpath"}}
*
* @apiSuccess {object} data contains schema requested
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 Success-response:
* {"status":200,"data":{schema}}
*/
router.get("schema/:objectname", checkHeaders, isAuthenticated, (req, res) => {
const fullpath = path.resolve(
`${__dirname}/tribes/${req.session.header.xworkon}/schema/${req.params.pathobjectname}.json`
@@ -219,33 +357,36 @@ router.get("schema/:objectname", checkHeaders, isAuthenticated, (req, res) => {
} else {
res
.status(404)
.json({ msg: "schemanotfound", ref: "odmdb", data: { fullpath } });
.json({ status:404, msg: "schemanotfound", ref: "odmdb", data: { fullpath } });
}
});
/**
* @api {put} /odmdb/schema/:objectname - schema Put
* @apiGroup Odmdb
* @apiName putSchema
* @apiDescription Replace a schema by another one need druid profil for a tribe
*
* @apiParam {String} objectname Mandatory
*
* @apiBody {string} schemapath where to store schema .../schema
* @apiBody {string} objectpath where to store object ...objectname/idx/conf.json
* @apiBody {json} schema content
* @apiBody {json} schemalang content in lg
* @apiBody {string} lang define which schemalg is (2 letters)
*
* @apiError {object} ref objectmodel to get in the right language
* @apiErrorExample {json} Error-response:
* HTTP/1.1 404 Not Found
* {"status":404,"ref":"Odmdb","msg":"schemanotfound","data":{"fullpath"}}
*
* @apiSuccess {object} data contains schema requested
* HTTP/1.1 200 Success-response:
* {"status":200,"data":{schema}}
*
*
*/
router.put("schema/:objectname", checkHeaders, isAuthenticated, (req, res) => {
/**
* @api {put} /odmdb/schema/:objectname
* @apiName putSchema
* @apiGroup Odmdb
*
* @apiUse apxHeader
*
* @apiParam {String} objectname Mandatory if headers.xworkon == nationchains then into ./nationchains/ else into ./tribes/xworkon/
* @apiBody {string} schemapath where to store schema .../schema
* @apiBody {string} objectpath where to store object ...objectname/idx/conf.json
* @apiBody {json} schema content
* @apiBody {json} schemalang content in lg
* @apiBody {string} lang define which schemalg is (2 letters)
*
* @apiError (404) {string} status a key word to understand not found schema
* @apiError (404) {string} ref objectmodel to get in the right language
* @apiError (404) {string} msg key to get template from objectmodel
* @apiError (404) {object} data use to render lg/objectmodel_lg.json
*
*
* @apiSuccess (200) {object} data contains schema requested
*
*/
const fullpath = path.resolve(
`${__dirname}/tribes/${req.session.header.xworkon}/schema/${req.params.pathobjectname}.json`
);
@@ -262,4 +403,34 @@ router.put("schema/:objectname", checkHeaders, isAuthenticated, (req, res) => {
}
});
/**
* @api {get} https://wall-ants.ndda.fr/nationchains/models/:modelname_lg.json - translation notif Get public
* @apiGroup Odmdb
* @apiName getPublicModelmessagekey
* @apiDescription Get a public json object for the ref: modelname in language lg, to get a template description with key msg
* @apiParam {string} modelname Mandatory
* @apiSuccess {json} contain json file
* @apiSuccessExample {json} Fichier direct
* HTTP/1.1 200 Success-response:
* {
"alreadyexist": "Un object {{objectname}} avec la clé {{key}} existe déjà avec {{val}}",
"doesnotexist": "L'object {{objectname}} avec la clé {{key}} ,'existe pas avec {{val}}",
"getschema": "Schema {{{conf.name}}}",
"schemanotfound": "Schema introuvable dans {{{schemaPath}}}",
"pathnamedoesnotexist": "Le repertoire n'existe pas {{{indexpath}}}",
"objectfiledoesnotexist": "Le fichier n'existe pas {{{objectpath}}}",
"cudsuccessfull": "Mise à jour effectuée avec succés",
"missingprimarykey": "Il manque une clé primaire apxid pour stocker et identifier les objects",
"unconsistencyapxidx": "L'index {{name}} doit contenir en objkey au moins {{apxid}} car keyval n'est pas unique",
"profilnotallow": "Vous n'avez pas le profil de {{profils}}, cette action n'est pas authorisée",
"successreindex": "Objet reindexé à partir des items, vos index sont à jour",
"indexexist":"L'indexe existe"
* }
* @apiError {json} contain json file
* @apiErrorExample {string} nginx html not found message
* HTTP/1.1 404 Not Found
* <html>...</html>
**/
module.exports = router;

View File

@@ -16,22 +16,40 @@ const router = express.Router();
* Managed:
/**
* @api {get} /pagans/alias/:alias
* @apiName Is register check xalias and xhash
* Alias exist then return public key or not
* @api {get} /pagans/alias/:alias - alias Get
* @apiName isalias
* @apiGroup Pagans
* @param {string} alias a alias that exist or not
* @apiSuccess (200) {object} {ref:"pagans",msg:"aliasexist",data: { alias, publicKey } }
* @apiError (404) {object} {ref:"pagans",msg:"aliasdoesnotexist",data: { alias} }
* @apiDescription If alias exist return its publickey
*
* @param {string} alias
*
* @apiError {json} aliasdoesnotexist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
{"status":404,"ref":"pagans","msg":"aliasdoesnotexist","data": { alias}}
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, ref:"pagans","msg":"aliasexist","data": { alias, publicKey }}
* *
**/
router.get("/alias/:alias", (req, res) => {
const getalias = Pagans.getalias(req.params.alias);
res.status(getalias.status).send(getalias);
});
/**
* @api {get} /pagans/logout
* @apiName Remove token
* Remove serveur token
* @api {get} /pagans/logout - pagan Logout
* @apiName Removetoken
* @apiGroup Pagans
* @apiDescription Remove token
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {status: 200, ref: "Pagans", msg: "logout"
*
*/
router.get("/logout", checkHeaders, isAuthenticated, (req, res) => {
@@ -44,41 +62,20 @@ router.get("/logout", checkHeaders, isAuthenticated, (req, res) => {
);
res.status(logout.status).json(logout);
});
/**
* @api {get} /pagans/person:alias
* @apiName Is register check xalias and xhash
* @api {get} /pagans/isauth - pagan isAuthenticated?
* @apiName isAuth
* @apiGroup Pagans
* @apiUse apxHeader
* @param {string} alias that exist
* @param {string} tribeId that exist with a person alias
* @apiSuccess (200) {ref:"pagans",msg:"personexist",data: { person } }
* @apiError (404) {ref:"pagans",msg:"persondoesnotexist",data: { person } }
* @apiDescription Check if pagan's token is still valid
*
* @todo check accessright for req.session.header.xalias to see if jhe can get person data
* if req.param.alias == req.session.header.xalias => Owner
* else need accessright to on person set at R
* */
router.get("/person/:alias", checkHeaders, isAuthenticated, (req, res) => {
const getperson = Pagans.getperson(
req.session.header.xtribe,
req.params.alias,
{ xprofils: req.session.header.xprofils, xalias: req.session.header.xalias }
);
res.status(getperson.status).send(getperson);
});
/**
* @api {get} /pagans/isauth
* @apiName Is register check xalias and xhash
* @apiGroup Pagans
* @apiUse apxHeader
* @apiError (400) missingheaders
* @apiError (400) xaliasdoesnotexist
* @apiError (400) signaturefailled
* @apiError (401) aliasanonymous
* @apiError (404) tribedoesnotexist
*
* @apiError (400) {object} status missingheaders / xalias does not exist / signaturefailled
* @apiError (401) {object} alias anonymous (not authenticated)
* @apiError (404) {string} tribe does not exist
*
* @apiSuccess (200) {object} data contains indexfile requested
* @apiSuccess (200) valid
* {object} data contains indexfile requested
*
*/
router.get("/isauth", checkHeaders, isAuthenticated, (req, res) => {
@@ -94,17 +91,27 @@ router.get("/isauth", checkHeaders, isAuthenticated, (req, res) => {
});
/**
* @api {post} /pagans
* @apiName Is register check xalias and xhash
* @api {post} /pagans - pagan Post
* @apiName addpagan
* @apiGroup Pagans
* @apiUse apxHeader
*
* Create a pagan account from alias, publickey, if trusted recovery =>
* @apiDescription
* Create a pagan account from alias, publickey, if trusted recovery =>
* Create a person in xtribe/person/xalias.json with profil.auth={email,privatekey, passphrase}
* Middleware isAuthenticated check that:
* Middleware isAuthenticated check that:
* - xhash is well signed from private key linked to the publickey of alias
* - check that alias does not already exist (if yes then verifiedsigne would be false)
* Need to wait next block chain to be sure that alias is register in the blokchain
*
* @apiError {json} objectNotfound the file does not exist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
{"status":404,"ref":"Odmdb","msg":"pathnamedoesnotexist","data":{indexpath}}
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"indexexist", "data":{indexname,content:{index file}}
*
*/
router.post("/", checkHeaders, isAuthenticated, (req, res) => {
//console.log("pass ici", req.body);
@@ -150,12 +157,61 @@ router.post("/", checkHeaders, isAuthenticated, (req, res) => {
}
});
/**
* @api {post} /pagans/person
* @apiName Is register check xalias and xhash
* @api {delete} /pagans/alias/:alias - pagan Delete
* @apiName deletepagan
* @apiGroup Pagans
* @apiDescription
* Delete an alias and his publickey
* */
router.delete("/alias/:alias", checkHeaders, isAuthenticated, (req, res) => {
console.log(`DELETE pagans nationchains/pagans/${req.params.alias}.json`);
const result = Pagans.deletealias(req.params.id, req.session.header);
res.status(result.status).send(result.data);
});
router.delete("/person/:alias", checkHeaders, isAuthenticated, (req, res) => {
console.log(`DELETE pagans nationchains/pagans/${req.params.alias}.json`);
const result = Pagans.deleteperson(req.params.id, req.session.header);
res.status(result.status).send(result.data);
});
/**
* @api {get} /pagans/person:alias - person Get
* @apiName getpersondata
* @apiDescription Get person information from his alias for a xtribe (data and profils per apps)
* @apiGroup Pagans
* @apiUse apxHeader
*
* @apiParam {string} alias
*
* @apiSuccess (200) personExist
* @apiSuccessExample {json}
* {status:200, ref:"pagans",msg:"personexist",data: { person } }
*
* @apiError (404) Notfound
* @apiErrorExample {json}
* {status: 404, ref:"pagans",msg:"persondoesnotexist",data: { person } }
*
* @todo check accessright for req.session.header.xalias to see if jhe can get person data
* if req.param.alias == req.session.header.xalias => Owner
* else need accessright to on person set at R
* */
router.get("/person/:alias", checkHeaders, isAuthenticated, (req, res) => {
const getperson = Pagans.getperson(
req.session.header.xtribe,
req.params.alias,
{ xprofils: req.session.header.xprofils, xalias: req.session.header.xalias }
);
res.status(getperson.status).send(getperson);
});
/**
* @api {post} /pagans/person - person Post
* @apiName addperson
* @apiGroup Pagans
* @apiDescription
* add a person = alias + tribe with specific accessright and specific schema link to tribe
*
*
*
* @todo add tribe/schema/person.json
*/
router.post("/person", checkHeaders, isAuthenticated, (req, res) => {
@@ -170,13 +226,13 @@ router.post("/person", checkHeaders, isAuthenticated, (req, res) => {
});
/**
* @api {put} /pagans/person
* @apiName Is register check xalias and xhash
* @api {put} /pagans/person - person Put
* @apiName updateperson
* @apiGroup Pagans
* @apiUse apxHeader
*
* @apiDescription
* 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
*/
router.put("/person", checkHeaders, isAuthenticated, (req, res) => {
//console.log(req.body);
@@ -189,30 +245,12 @@ router.put("/person", checkHeaders, isAuthenticated, (req, res) => {
res.status(persoup.status).json(persoup);
});
/**
* @api {delete} /pagans/alias/:alias
* @apiName Is register check xalias and xhash
* @apiGroup Pagans
* @apiUse apxHeader
* */
router.delete("/alias/:alias", checkHeaders, isAuthenticated, (req, res) => {
console.log(`DELETE pagans nationchains/pagans/${req.params.alias}.json`);
const result = Pagans.deletealias(req.params.id, req.session.header);
res.status(result.status).send(result.data);
});
router.delete("/person/:alias", checkHeaders, isAuthenticated, (req, res) => {
console.log(`DELETE pagans nationchains/pagans/${req.params.alias}.json`);
const result = Pagans.deleteperson(req.params.id, req.session.header);
res.status(result.status).send(result.data);
});
/**
* @api {get} /pagans/keyrecovery/tribe/email
* @apiName apxtrib
* @api {get} /pagans/keyrecovery/tribe/email - recovery key by email
* @apiName recoveryKey
* @apiGroup Pagans
*
*
*
* @apiError (400) {object} status missingheaders / xalias does not exist / signaturefailled
* @apiError (401) {object} alias anonymous (not authenticated)
* @apiError (404) {string} tribe does not exist

82
api/routes/trackings.js Normal file
View File

@@ -0,0 +1,82 @@
const express = require("express");
const glob = require("glob");
const fs = require("fs-extra");
const path = require("path");
const conf = require(`${process.env.dirtown}/conf.json`);
const Odmdb = require("../models/Odmdb.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const router = express.Router();
/**
* @api {get} https://dns.xx/trk/pathtofile? - tracking system
* @apiGroup Trackings
* @apiName trackingsystem
* @apiDescription
* without header:<br>
* <code>https://dns.xx/trk/pathtofile?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&src=btnregister&version=1&lg=fr </code>
*
* with header<br>
* <code>https://dns.xx/trk/pathtofile?srckey=btnregister&version=1</code>
*
* where pathtofile is a ressource accessible from https://dns.xx/pathtofile
* html usage to track a loading page or email when a picture is load
* using apxwebapp in /src/ we got:
* <code> < img src="static/img/photo.jpg" data-trksrckey="loadpage" data-version="1" > </code>
*
* using html + apx.js (or at least with header {xalias,xuuid,xlang})
* <code>< img lazysrc="trk/static/img/photo.jpg data-trksrckey="loadpage" data-version="1" ></code>
*
* in js action:
*
* <code>
* <button></button>
* <a data-trksrckey="linktoblabla" href='https:..'
* onclick="apx.trackvisit("btnaction",1);actionfct();">
* </a>
* </code>
* #will hit an eventlistener<br>
* <code> axios.get("https://dns.xx/trk/cdn/empty.json?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&srckey=btnregister&version=1");
* </code>
*
* #or if no js available (example:email or pdf document)<br>
* <code> < img src="https://dns.xx/trk/static/img/photo.jpg?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&srckey=loadpage&version=1"</code>
*
* <code>
* <a href="https://dns.xx/trk/redirect?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&srckey=loadpage&version=1&url=http://..."
* </code>
*
* will hit a tracker then redirect to url></a> *
*
*
*
* **if you use apx.js** : in html add in < button >, < img >, < a > tag data-trksrc="srckey"
* <code>
* < img src="https://dns.xx/static/img/photo.jpg" data-trkversion="1" data-trksrckey="registerform">
* < button data-trksrc="https://dns.xx/static/img/photo.jpg" data-trkversion="1" data-trksrckey="registerform">
* </code>
*
* Tracking log are store into tribe/logs/nginx/tribe_appname.trk.log
* Src have to be manage in tribe/api/models/lg/src_en.json
* <code>{"srckey":{
* "app":"presentation|app|apptest",
* "title":"",
* "description":""
* }
* }
* </code>
*
* @apiParam {String} alias=anonymous if authenticated we get from headers
* @apiParam {String} uuid a uuid v4 generate the first time a web page is open on a browser
* @apiParam {String} srckey source action that trig this get
* @apiParam {integer} version=1 can be an int, date or any version of the src
* @apiParam {integer} [tm] a timestamp of action when it is not immediate (for offline app)
*
*/
module.exports=router;

View File

@@ -8,6 +8,7 @@ const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const router = express.Router();
/**
* To manage an nginx conf
*

58
api/test/notifications.js Normal file
View File

@@ -0,0 +1,58 @@
const express = require("express");
const fs = require("fs-extra");
const path = require("path");
// Classes
const Pagans = require("../models/Notifications.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const router = express.Router();
/**
* Get form data and send notification to user by email, sms, alert
* @api{post}/messageanonymous
* @apiName Notification
* @apiDescription Send information as anonymous to tribe's druid
* @apiGroup apxtrib
*
* @apiUse apxHeader
* @apiParam {string} objectname Mandatory
* @apiParam {String} indexname Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname/idx/indexname indexname contains the ObjectName .*_ (before the first _)
*
*
* @apiError {json} objectNotfound the file does not exist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
{"status":404,"ref":"Odmdb","msg":"pathnamedoesnotexist","data":{indexpath}}
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"indexexist", "data":{indexname,content:{index file}}
*
*
**/
router.get("/alias/:alias", (req, res) => {
const getalias = Pagans.getalias(req.params.alias);
res.status(getalias.status).send(getalias);
});
/**
* Remove serveur token
* @api {get} /pagans/logout
* @apiName Remove token
* @apiGroup Pagans
*
*/
router.get("/logout", checkHeaders, isAuthenticated, (req, res) => {
console.log(req.session.header);
const logout = Pagans.logout(
req.session.header.xalias,
req.session.header.xtribe,
req.session.header.xdays,
req.session.header.xhash
);
res.status(logout.status).json(logout);
});

437
api/test/odmdb.js Normal file
View File

@@ -0,0 +1,437 @@
const express = require("express");
const glob = require("glob");
const fs = require("fs-extra");
const path = require("path");
const conf = require(`${process.env.dirtown}/conf.json`);
const Odmdb = require("../models/Odmdb.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const router = express.Router();
/**
* @api{get}/odmdb/idx/:objectname/:indexname - index Get
* @apiGroup Odmdb
* @apiName getIndex
* @apiDescription Get index file for an object
*
* @apiParam {string} objectname If in conf.nationObjects then object is into nationchains/ else in tribes/xtribe/objectname/idx/indexname indexname
* @apiParam {String} indexname name of index file in /idx/indexnamme.json
*
*
* @apiError {json} objectNotfound the file does not exist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
{"status":404,"ref":"Odmdb","msg":"pathnamedoesnotexist","data":{indexpath}}
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"indexexist", "data":{indexname,content:{index file}}
*
*
*/
router.get(
"/idx/:objectname/:indexname",
checkHeaders,
isAuthenticated,
(req, res) => {
console.log("passe");
// indexname = objectname_key_value.json
let objectLocation = "../../nationchains/";
if (!conf.api.nationObjects.includes(req.params.objectname)) {
objectLocation += `tribes/${req.session.headers.xtribe}/`;
// check if accessright
}
const indexpath = `${objectLocation}/${req.params.objectname}/idx/${req.params.indexname}`;
if (fs.existsSync(indexpath)) {
res
.status(200)
.json({
ref: "Odmdb",
msg: "indexexist",
data: {
indexname: req.params.indexname,
content: fs.readJsonSync(indexpath),
},
});
} else {
res.status(404).json({
ref: "Odmdb",
msg: "pathnamedoesnotexist",
data: { indexpath },
});
}
}
);
/**
* @api {get} /odmdb/rebuildidx/:objectname - index refresh all
* @apiGroup Odmdb
* @apiName refreshAllIndex
* @apiDescription Rebuild all index for an object, this can be usefull in case crash or any data conflict.
*
* @apiParam {string} objectname Mandatory
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"successreindex", "data":{"indexlist":[]}}
*
* @apiError {json} objectNotfound the file does not exist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
{"status":404,"ref":"Odmdb","msg":"see nationchains/model/lg/Odmdb_xx.json","data":"object to render with msg"}
*
*/
router.get(
"/rebuildidx/:objectname",
checkHeaders,
isAuthenticated,
(req, res) => {
console.log("reindex");
// check validity and accessright
const objectPathname = conf.api.nationObjects.includes(
req.params.objectname
)
? `${conf.dirapi}/nationchains/${req.params.objectname}`
: `${conf.dirtown}/tribes/${req.session.header.xtribe}/${req.params.objectname}`;
//console.log(objectPathname);
if (!fs.existsSync(objectPathname)) {
res.status(404).json({
status: 404,
ref: "Odmdb",
msg: "pathnamedoesnotexist",
data: { indexpath: objectPathname },
});
return false;
}
if (
conf.api.nationObjects.includes(req.params.objectname) &&
!req.session.header.xprofils.includes("mayor")
) {
res.status(403).json({
status: 403,
ref: "Odmdb",
msg: "profilnotallow",
data: { profils: "mayor" },
});
return false;
}
if (
!conf.api.nationObjects.includes(req.params.objectname) &&
!req.session.header.xprofils.includes("druid")
) {
res.status(403).json({
status: 403,
ref: "Odmdb",
msg: "profilnotallow",
data: { profils: "druid" },
});
return false;
}
const reindex = Odmdb.idxfromitm(objectPathname, "I", {}, {}, [], {});
res.status(reindex.status).json(reindex);
}
);
/**
* @api {post} /odmdb/itm/:objectname - item Create
* @apiGroup Odmdb
* @apiName postItm
* @apiPermission none
* @apiDescription Add an new item (data) into a collection of objectname items. Before Check data integrity with the relevant schema.
* Then create a new primarykey. For multilanguage return see nationchains/model/lg/Odmdb_xx.json.
*
* @apiParam {string} objectname Place where to create new item, schema and version are available in /objectname/conf.json
*
* @apiBody {Object} data must pass Checkjson.js with schema
*
* @apiSuccess {json} data idxprimary Value of idxprimary into objectname collection
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"cudsuccessfull", "data":{"itm":{}}}
*
* @apiError {json} schemanotfound The objectname schema is not found
* @apiError {json} pathnamedoesnotexist The objectname does not exist for the tribe
* @apiError {json} missingprimarykey Body data must have primarykey to be created
* @apiError {json} unconsistencyapxidx some Body data get unique key that already exist
* @apiError {json} checkjsonfalse The body data are not consistent with the schema
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
* {"status":404,"ref":"Odmdb","msg":"see nationchains/model/lg/Odmdb_xx.json","data":"object to render with msg"}
*
*/
router.post("/itm/:objectname", checkHeaders, isAuthenticated, (req, res) => {
// Create an item of an object with no specificities
// if specificities then create a route / model that import odmdb
});
router.get(
"/searchitems/:objectname/:question",
checkHeaders,
isAuthenticated,
(req, res) => {
/**
*
*
*/
console.log(
"route referentials get all language" +
req.params.objectname +
"-" +
req.params.question
);
const getref = Referentials.getref(
true,
req.params.source,
req.params.idref,
req.session.header.xworkon,
req.session.header.xlang
);
// Return any status the data if any erreur return empty object
res.jsonp(getref.payload.data);
}
);
/**
* @api {get} /odmdb/itm/:objectname/:primaryindex - item Get
* @apiGroup Odmdb
* @apiName getItemFromId
* @apiDescription Get itm for a primaryid of an object
*
* @apiParam {String} objectname name Mandatory if in conf.nationObjects then file is into nationchains/ else in /nationchains/tribes/xtribe/objectname
* @apiParam {String} primaryindex the unique id where item is store
*
* @apiError {json} objectNotfound the file item does not exist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
* {"status":404,"ref":"Odmdb","msg":"doesnotexist","data":{"objectname":"objectname","key":"apxid","val":"primaryindex"}}
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"indexexist", "data":{"indexname","content":{itm file}}
*
*
*/
// indexname = objectname_key_value.json
router.get(
"/itm/:objectname/:primaryindex",
checkHeaders,
isAuthenticated,
(req, res) => {
const objectName = req.params.objectname;
const objectId = req.params.primaryindex;
let objectLocation = "../../nationchains/";
if (!conf.api.nationObjects.includes(objectName)) {
objectLocation += `tribes/${req.session.headers.xtribe}/${objectName}`;
// check if accessright on object on item
// in case not res.status(403)
}
const objectpath = `${objectLocation}/${objectName}/itm/${objectId}`;
if (fs.existsSync(objectpath)) {
res.status(200).json({ data: fs.readJsonSync(objectpath) });
} else {
res.status(404).json({
ref: "Odmdb",
msg: "objectfiledoesnotexist",
data: { objectpath },
});
}
}
);
/**
* @api {get} https://wall-ants.ndda.fr/Checkjson.js - schema check data lib
* @apiGroup Odmdb
* @apiName checkjsonjs
* @apiDescription Public js lib to import in a browser by :<br>
* ```<script src="wall-ants.ndda.fr/nationchains/contracts/Checkjson.js"></script>```
* to import in a node.js:<br>
* ```const Checkjson = require(`Checkjson.js`);```
*
* with functions:<br>
* <strong>Checkjson.schema.validation(schema)</strong> that return<br>
* - {status:200, ref:"Checkjson", msg:"validcheck"} => all rules are correct<br>
* - {status:406, multimsg:[{ref:"Checkjson",msg:"errorkey",data:{}}]}<br>
*
* <strong>Checkjson.schema.data(schema{json},data{json},withschemacheck{boolean})</strong> that return<br>
* - {status:200, ref:"Checkjson", msg:"validcheck"} => all data keys respect schema rules <br>
* - {status:417, multimsg:[{ref:"Checkjson",msg:"errorkey",data:{}}]}<br>
*
* To identify issues, get the language errorkey list with a get
* https://wall-ants.ndda.fr/nationchains/models/Checkjson_lg.json
*
*/
/**
* @api {get} https://wall-ants.ndda.fr/nationchains/schema/:objectname - schema Get public
* @apiGroup Odmdb
* @apiName getPublicSchema
* @apiDescription Get a Schema model from public apxtrib (nations, pagans,persons,towns, tribes,wwws)
* @apiSuccess {json} contain json file
* @apiSuccessExample {json} Fichier direct
* HTTP/1.1 200 Success-response:
{
"$id": "https://smatchit.io/schema/pagan",
"$comment": "To create account bin apxtrib",
"title": "Pagans identity",
"description": "A numeric id in the nationchains world",
"type": "object",
"properties": {
"publickey": {
"title": "Alias's publickey",
"description": "Public key generate with openpgp.js",
"type": "string",
"format": "pgppublickey"
},
"alias": {
"title": "Alias",
"description": "text to remember easily a public key",
"type": "string",
"minLength": 4,
"pattern": "^[a-z0-9]*$"
},
"dt_delete": {
"title": "Date of death",
"description": "Date of alias delete request, your will will be apply",
"type": "string",
"format": "date-time"
},
"will": {
"title": "Will script after death",
"description": "This will script will be apply on your data 30 days after your death",
"type": "string"
}
},
"required": ["publickey", "alias"],
"apxid": "alias",
"apxuniquekey": ["publickey"],
"apxidx": [
{ "name": "lst_alias", "keyval": "alias" },
{ "name": "alias", "keyval": "alias" }
],
"apxaccessrights": {
"owner": { "R": [], "D": [] },
"anonymous": { "C": [], "R": ["alias"] },
"pagan": { "R": ["alias", "publickey"] }
}
}
* @apiError {json} contain json file
* @apiErrorExample {string} nginx html not found message
* HTTP/1.1 404 Not Found
* <html>...</html>
**/
/**
* @api {get} /odmdb/schema/:objectname - schema Get private
* @apiGroup Odmdb
* @apiName getPrivateSchema
* @apiDescription Get a private (profil must have accessright R on object) to a Schema model
*
* @apiParam {String} objectname Mandatory
*
* @apiError {object} ref objectmodel to get in the right language
* @apiErrorExample {json} Error-response:
* HTTP/1.1 404 Not Found
* {"status":404,"ref":"Odmdb","msg":"schemanotfound","data":{"fullpath"}}
*
* @apiSuccess {object} data contains schema requested
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 Success-response:
* {"status":200,"data":{schema}}
*/
router.get("schema/:objectname", checkHeaders, isAuthenticated, (req, res) => {
const fullpath = path.resolve(
`${__dirname}/tribes/${req.session.header.xworkon}/schema/${req.params.pathobjectname}.json`
);
if (fs.existsSync(fullpath)) {
res.status(200).json({ data: fs.readJsonSync(fullpath) });
} else {
res
.status(404)
.json({ status:404, msg: "schemanotfound", ref: "odmdb", data: { fullpath } });
}
});
/**
* @api {put} /odmdb/schema/:objectname - schema Put
* @apiGroup Odmdb
* @apiName putSchema
* @apiDescription Replace a schema by another one need druid profil for a tribe
*
* @apiParam {String} objectname Mandatory
*
* @apiBody {string} schemapath where to store schema .../schema
* @apiBody {string} objectpath where to store object ...objectname/idx/conf.json
* @apiBody {json} schema content
* @apiBody {json} schemalang content in lg
* @apiBody {string} lang define which schemalg is (2 letters)
*
* @apiError {object} ref objectmodel to get in the right language
* @apiErrorExample {json} Error-response:
* HTTP/1.1 404 Not Found
* {"status":404,"ref":"Odmdb","msg":"schemanotfound","data":{"fullpath"}}
*
* @apiSuccess {object} data contains schema requested
* HTTP/1.1 200 Success-response:
* {"status":200,"data":{schema}}
*
*
*/
router.put("schema/:objectname", checkHeaders, isAuthenticated, (req, res) => {
const fullpath = path.resolve(
`${__dirname}/tribes/${req.session.header.xworkon}/schema/${req.params.pathobjectname}.json`
);
const set = Odmdb.setObject(
path.resolve(`${__dirname}/tribes/${req.session.header.xworkon}`)
);
if (fs.existsSync(fullpath)) {
res.status(200).json({ data: fs.readJsonSync(fullpath) });
} else {
res
.status(404)
.json({ msg: "schemanotfound", ref: "odmdb", data: { fullpath } });
}
});
/**
* @api {get} https://wall-ants.ndda.fr/nationchains/models/:modelname_lg.json - translation notif Get public
* @apiGroup Odmdb
* @apiName getPublicModelmessagekey
* @apiDescription Get a public json object for the ref: modelname in language lg, to get a template description with key msg
* @apiParam {string} modelname Mandatory
* @apiSuccess {json} contain json file
* @apiSuccessExample {json} Fichier direct
* HTTP/1.1 200 Success-response:
* {
"alreadyexist": "Un object {{objectname}} avec la clé {{key}} existe déjà avec {{val}}",
"doesnotexist": "L'object {{objectname}} avec la clé {{key}} ,'existe pas avec {{val}}",
"getschema": "Schema {{{conf.name}}}",
"schemanotfound": "Schema introuvable dans {{{schemaPath}}}",
"pathnamedoesnotexist": "Le repertoire n'existe pas {{{indexpath}}}",
"objectfiledoesnotexist": "Le fichier n'existe pas {{{objectpath}}}",
"cudsuccessfull": "Mise à jour effectuée avec succés",
"missingprimarykey": "Il manque une clé primaire apxid pour stocker et identifier les objects",
"unconsistencyapxidx": "L'index {{name}} doit contenir en objkey au moins {{apxid}} car keyval n'est pas unique",
"profilnotallow": "Vous n'avez pas le profil de {{profils}}, cette action n'est pas authorisée",
"successreindex": "Objet reindexé à partir des items, vos index sont à jour",
"indexexist":"L'indexe existe"
}
* @apiError {json} contain json file
* @apiErrorExample {string} nginx html not found message
* HTTP/1.1 404 Not Found
* <html>...</html>
**/
module.exports = router;

264
api/test/pagans.js Executable file
View File

@@ -0,0 +1,264 @@
const express = require("express");
const fs = require("fs-extra");
const path = require("path");
// Classes
const Pagans = require("../models/Pagans.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const router = express.Router();
/**
* /api/models/Pagans.js
*
* Managed:
/**
* Alias exist then return public key or not
* @api {get} /pagans/alias/:alias - alias Get
* @apiName isalias
* @apiGroup Pagans
* @apiDescription If alias exist return its publickey
*
* @param {string} alias
*
* @apiError {json} aliasdoesnotexist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
{"status":404,"ref":"pagans","msg":"aliasdoesnotexist","data": { alias}}
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, ref:"pagans","msg":"aliasexist","data": { alias, publicKey }}
* *
**/
router.get("/alias/:alias", (req, res) => {
const getalias = Pagans.getalias(req.params.alias);
res.status(getalias.status).send(getalias);
});
/**
* Remove serveur token
* @api {get} /pagans/logout - pagan Logout
* @apiName Removetoken
* @apiGroup Pagans
* @apiDescription Remove token
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {status: 200, ref: "Pagans", msg: "logout"
*
*/
router.get("/logout", checkHeaders, isAuthenticated, (req, res) => {
console.log(req.session.header);
const logout = Pagans.logout(
req.session.header.xalias,
req.session.header.xtribe,
req.session.header.xdays,
req.session.header.xhash
);
res.status(logout.status).json(logout);
});
/**
* @api {get} /pagans/isauth - pagan isAuthenticated?
* @apiName isAuth
* @apiGroup Pagans
* @apiDescription Check if pagan's token is still valid
*
* @apiError (400) missingheaders
* @apiError (400) xaliasdoesnotexist
* @apiError (400) signaturefailled
* @apiError (401) aliasanonymous
* @apiError (404) tribedoesnotexist
*
* @apiSuccess (200) valid
* {object} data contains indexfile requested
*
*/
router.get("/isauth", checkHeaders, isAuthenticated, (req, res) => {
res.status(200).send({
status: 200,
ref: "headers",
msg: "authenticated",
data: {
xalias: req.session.header.xalias,
xprofils: req.session.header.xprofils,
},
});
});
/**
* @api {post} /pagans - pagan Post
* @apiName addpagan
* @apiGroup Pagans
* @apiDescription
* Create a pagan account from alias, publickey, if trusted recovery =>
* Create a person in xtribe/person/xalias.json with profil.auth={email,privatekey, passphrase}
* Middleware isAuthenticated check that:
* - xhash is well signed from private key linked to the publickey of alias
* - check that alias does not already exist (if yes then verifiedsigne would be false)
* Need to wait next block chain to be sure that alias is register in the blokchain
*
* @apiError {json} objectNotfound the file does not exist
* @apiErrorExample {json}
* HTTP/1.1 404 Not Found
{"status":404,"ref":"Odmdb","msg":"pathnamedoesnotexist","data":{indexpath}}
*
* @apiSuccess {object} indexfile content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {"status":200, "ref":"Odmdb", "msg":"indexexist", "data":{indexname,content:{index file}}
*
*/
router.post("/", checkHeaders, isAuthenticated, (req, res) => {
//console.log("pass ici", req.body);
const objpagan = { alias: req.body.alias, publickey: req.body.publickey };
const newpagan = Pagans.create(objpagan, {
xalias: req.session.header.xalias,
xprofils: req.session.header.xprofils,
});
if (newpagan.status == 200) {
if (req.body.email) {
const emailsent = Pagans.sendmailkey(
req.body.alias,
req.body.privatekey,
req.session.header.xtribe,
req.body.passphrase,
req.body.publickey,
req.body.email
);
}
if (req.body.trustedtribe) {
const personup = Pagans.personupdate(
req.body.alias,
req.body.trustedtribe,
{
recoveryauth: {
email: req.body.email,
privatekey: req.body.privatekey,
publickey: req.body.publickey,
passphrase: req.body.passphrase,
},
}
);
if (personup.status !== 200)
console.log("Warning no recovery registration", personup);
}
if (emailsent && emailsent.status != 200) {
newpagan.msg = "successfulcreatewithoutemail";
res.status(newpagan.status).json(newpagan);
}
} else {
//error to create pagan certaily already exist
res.status(newpagan.status).json(newpagan);
}
});
/**
* @api {delete} /pagans/alias/:alias - pagan Delete
* @apiName deletepagan
* @apiGroup Pagans
* @apiDescription
* Delete an alias and his publickey
* */
router.delete("/alias/:alias", checkHeaders, isAuthenticated, (req, res) => {
console.log(`DELETE pagans nationchains/pagans/${req.params.alias}.json`);
const result = Pagans.deletealias(req.params.id, req.session.header);
res.status(result.status).send(result.data);
});
router.delete("/person/:alias", checkHeaders, isAuthenticated, (req, res) => {
console.log(`DELETE pagans nationchains/pagans/${req.params.alias}.json`);
const result = Pagans.deleteperson(req.params.id, req.session.header);
res.status(result.status).send(result.data);
});
/**
* @api {get} /pagans/person:alias - person Get
* @apiName getpersondata
* @apiDescription Get person information from his alias for a xtribe (data and profils per apps)
* @apiGroup Pagans
*
* @apiParam {string} alias
*
* @apiSuccess (200) personExist
* @apiSuccessExample {json}
* {status:200, ref:"pagans",msg:"personexist",data: { person } }
*
* @apiError (404) Notfound
* @apiErrorExample {json}
* {status: 404, ref:"pagans",msg:"persondoesnotexist",data: { person } }
*
* @todo check accessright for req.session.header.xalias to see if jhe can get person data
* if req.param.alias == req.session.header.xalias => Owner
* else need accessright to on person set at R
* */
router.get("/person/:alias", checkHeaders, isAuthenticated, (req, res) => {
const getperson = Pagans.getperson(
req.session.header.xtribe,
req.params.alias,
{ xprofils: req.session.header.xprofils, xalias: req.session.header.xalias }
);
res.status(getperson.status).send(getperson);
});
/**
* @api {post} /pagans/person - person Post
* @apiName addperson
* @apiGroup Pagans
* @apiDescription
* add a person = alias + tribe with specific accessright and specific schema link to tribe
*
*
*
* @todo add tribe/schema/person.json
*/
router.post("/person", checkHeaders, isAuthenticated, (req, res) => {
//console.log(req.body);
const persoad = Pagans.personcreate(
req.session.header.xtribe,
req.body.alias,
req.body,
{ xprofils: req.session.header.xprofils, xalias: req.session.header.xalias }
);
res.status(persoad.status).json(persoad);
});
/**
* @api {put} /pagans/person - person Put
* @apiName updateperson
* @apiGroup Pagans
* @apiDescription
* update a person = alias + tribe with specific accessright and specific schema link to tribe
* @todo add tribe/schema/person.json
*/
router.put("/person", checkHeaders, isAuthenticated, (req, res) => {
//console.log(req.body);
const persoup = Pagans.personupdate(
req.session.header.xtribe,
req.body.alias,
req.body,
{ xprofils: req.session.header.xprofils, xalias: req.session.header.xalias }
);
res.status(persoup.status).json(persoup);
});
/**
* @api {get} /pagans/keyrecovery/tribe/email - recovery key by email
* @apiName recoveryKey
* @apiGroup Pagans
*
* @apiError (400) {object} status missingheaders / xalias does not exist / signaturefailled
* @apiError (401) {object} alias anonymous (not authenticated)
* @apiError (404) {string} tribe does not exist
*
* @apiSuccess (200) {object} data contains indexfile requested
*
*/
router.get("/keyrecovery/:tribeid/:email", checkHeaders, (req, res) => {
res.send(Pagans.keyrecovery(req.params.tribeId, req.params.email));
});
module.exports = router;

82
api/test/trackings.js Normal file
View File

@@ -0,0 +1,82 @@
const express = require("express");
const glob = require("glob");
const fs = require("fs-extra");
const path = require("path");
const conf = require(`${process.env.dirtown}/conf.json`);
const Odmdb = require("../models/Odmdb.js");
// Middlewares
const checkHeaders = require("../middlewares/checkHeaders");
const isAuthenticated = require("../middlewares/isAuthenticated");
const router = express.Router();
/**
* @api {get} https://dns.xx/trk/pathtofile? - tracking system
* @apiGroup Trackings
* @apiName trackingsystem
* @apiDescription
* without header:<br>
* <code>https://dns.xx/trk/pathtofile?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&src=btnregister&version=1&lg=fr </code>
*
* with header<br>
* <code>https://dns.xx/trk/pathtofile?srckey=btnregister&version=1</code>
*
* where pathtofile is a ressource accessible from https://dns.xx/pathtofile
* html usage to track a loading page or email when a picture is load
* using apxwebapp in /src/ we got:
* <code> < img src="static/img/photo.jpg" data-trksrckey="loadpage" data-version="1" > </code>
*
* using html + apx.js (or at least with header {xalias,xuuid,xlang})
* <code>< img lazysrc="trk/static/img/photo.jpg data-trksrckey="loadpage" data-version="1" ></code>
*
* in js action:
*
* <code>
* <button></button>
* <a data-trksrckey="linktoblabla" href='https:..'
* onclick="apx.trackvisit("btnaction",1);actionfct();">
* </a>
* </code>
* #will hit an eventlistener<br>
* <code> axios.get("https://dns.xx/trk/cdn/empty.json?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&srckey=btnregister&version=1");
* </code>
*
* #or if no js available (example:email or pdf document)<br>
* <code> < img src="https://dns.xx/trk/static/img/photo.jpg?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&srckey=loadpage&version=1"</code>
*
* <code>
* <a href="https://dns.xx/trk/redirect?alias=anonymous&uuid=1b506f71-1bff-416c-9057-cb8b86296f60&srckey=loadpage&version=1&url=http://..."
* </code>
*
* will hit a tracker then redirect to url></a> *
*
*
*
* **if you use apx.js** : in html add in < button >, < img >, < a > tag data-trksrc="srckey"
* <code>
* < img src="https://dns.xx/static/img/photo.jpg" data-trkversion="1" data-trksrckey="registerform">
* < button data-trksrc="https://dns.xx/static/img/photo.jpg" data-trkversion="1" data-trksrckey="registerform">
* </code>
*
* Tracking log are store into tribe/logs/nginx/tribe_appname.trk.log
* Src have to be manage in tribe/api/models/lg/src_en.json
* <code>{"srckey":{
* "app":"presentation|app|apptest",
* "title":"",
* "description":""
* }
* }
* </code>
*
* @apiParam {String} alias=anonymous if authenticated we get from headers
* @apiParam {String} uuid a uuid v4 generate the first time a web page is open on a browser
* @apiParam {String} srckey source action that trig this get
* @apiParam {integer} version=1 can be an int, date or any version of the src
* @apiParam {integer} [tm] a timestamp of action when it is not immediate (for offline app)
*
*/
module.exports=router;