apxtrib/app/middlewares/checkHeaders.js

90 lines
3.0 KiB
JavaScript
Raw Normal View History

2023-04-13 05:46:35 +00:00
const path = require( 'path' );
const config = require( '../tribes/townconf.js' );
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 config.languagesAvailable
*
* @apiHeader {string} xauth Pagans unique jwt token store in local town Pagans data or "noauth"
* @apiHeader {string} xpaganid 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 Pagan belong to
* @apiHeader {string} xworkon Tribes on which pagansId want and have accessright to work on.
* @apiHeader {string} xapp Name of app that send the request (tribesId:websiteName) cpaganid have to have accessright on this app}
*
* @apiError missingexposedHeaders it miss an exposedHeaders
*
* @apiErrorExample {json} Error-Response:
* HTTP/1/1 404 Not Found
* {
* status:404,
* info:"|middleware|missingheaders",
* moreinfo: xpaganid xauth
* }
*
* @apiHeaderExample {json} Header-Exemple:
* {
* xtribe:"apache",
* xpaganid:"12123211222",
* xworkon:"sioux",
* xauth:"",
* xlang:"en",
* xapp:""
* }
*/
req.session = {};
const header = {};
if (!req.header('xlang') && req.header('Content-Language')) req.params.xlang=req.header('Content-Language');
let missingheader = [];
for( const h of config.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 {
missingheade.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"
info: "missingheader",
moreinfo: missingheader
} );
};
//console.log( req.app.locals.tribeids )
if( !req.app.locals.tribeids.includes( header.xtribe ) ) {
return res.status( 400 )
.json( {
ref:"headers"
info: 'tribeiddoesnotexist',
moreinfo: header.xtribe
} );
}
if( !req.app.locals.tribeids.includes( header.xworkon ) ) {
return res.status( 400 )
.send( {
info: [ 'workondoesnotexist' ],
ref: 'headers',
moreinfo:header.xworkon
} );
}
if( !config.languages.includes( header.xlang ) ) {
header.xlang="en";
}
next();
};
module.exports = checkHeaders;