apxtrib/api/middlewares/checkHeaders.js
2023-04-27 06:17:20 +02:00

83 lines
2.8 KiB
JavaScript
Executable File

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