apxtrib/apxtrib.js
2023-04-28 13:21:02 +02:00

138 lines
5.8 KiB
JavaScript
Executable File

const fs = require( 'fs-extra' );
const bodyParser = require( 'body-parser' );
const glob = require( 'glob' );
const path = require( 'path' );
const cors = require( 'cors' );
const express = require( 'express' );
const process = require('process');
/*******************************************
SEE https://gitea.ndda.fr/apxtrib/apxtrib/wiki/Devrules
To have a quick understanding and convention before doing deeply in source code
*/
// to make absolute path with `${__base}relativepath`
global.__base = __dirname +'/';
// check setup
if( !fs.existsSync( '/etc/nginx/nginx.conf' ) ) {
console.log( '\x1b[31m Check documentation, nginx have to be installed on this server first, no /etc/nginx/nginx.conf available, install then rerun yarn command.' );
process.exit();
}
if( !fs.existsSync( './nationchains/tribes/conf.json' ) ) {
// this town is not set
console.log( `\x1b[42m############################################################################################\x1b[0m\n\x1b[42mWellcome into apxtrib, you must first init your town and tribes by a 'yarn setup'. \x1b[0m \n\x1b[42mThen 'yarn dev' or 'yarn startpm2' or 'yarn unittest'. Check README's project to learn more.\x1b[0m\n\x1b[42m############################################################################################\x1b[0m` );
process.exit();
}
const conf = require( './nationchains/tribes/conf.json' );
// To make public this conf, careffull this localconf will be public, this the only difference between all apxtrib node
const localconf={nationId:conf.nationId,townId:conf.townId,tribeId:conf.tribeId,comment:"Generate by apxtrib.js with minimum of information"};
fs.outputJsonSync('./nationchains/www/adminapx/static/tpldata/conf_en.json',localconf);
// Tribes allow to get local apxtrib instance context
// dataclient .tribeids [] .DOMs [] .routes (plugins {url:name route:path}) .appname {tribeid:[website]}
//const dataclient = require( './api/models/Tribes' ).init();
const tribelist=fs.readJsonSync(`./nationchains/tribes/idx/tribeId_all.json`);
let doms=conf.dns
let tribeIds=[]
let routes = glob.sync( './api/routes/*.js' )
.map( f => {
return { url: `/${path.basename(f,'.js')}`, route: f }
} );
//routes={url,route} check how to add plugin tribe route
Object.keys(tribelist).forEach(t=>{
tribelist[t].dns.forEach(d=>{
const dm=d.split('.').slice(-2).join('.')
if (!doms.includes(dm)) doms.push(dm)
})
tribeIds.push(t)
})
console.log('Allowed DOMs to access to this apxtrib server: ', doms )
const app = express();
Object.keys(conf.api.appset).forEach(p=>{
app.set(p,conf.api.appset[p])
})
// To set depending of data form or get size to send
app.use( bodyParser.urlencoded( conf.api.bodyparse.urlencoded ) );
// To set depending of post put json data size to send
app.use( express.json() )
app.use( bodyParser.json( conf.api.bodyparse.json ) );
app.locals.tribeids = tribeIds;
console.log( 'app.locals.tribeids', app.locals.tribeids );
// token will be store in /tmp/token/pseudo_token to check if isauthenticated
// User token authentification and user init user search
/*const datauser = require( './api/models/Pagans' )
.init( dataclient.tribeids );
app.locals.tokens = datauser.tokens;
console.log( 'app.locals.tokens key ', Object.keys( app.locals.tokens ) )
*/
// Cors management
const corsOptions = {
origin: ( origin, callback ) => {
if( origin === undefined ) {
callback( null, true );
} else if( origin.indexOf( 'chrome-extension' ) > -1 ) {
callback( null, true );
} else {
//console.log( 'origin', origin )
//marchais avant modif eslint const rematch = ( /^https?\:\/\/(.*)\:.*/g ).exec( origin )
const rematch = ( /^https?:\/\/(.*):.*/g )
.exec( origin )
//console.log( rematch )
let tmp = origin.replace( /http.?:\/\//g, '' )
.split( '.' )
if( rematch && rematch.length > 1 ) tmp = rematch[ 1 ].split( '.' );
//console.log( 'tmp', tmp )
let dom = tmp[ tmp.length - 1 ];
if( tmp.length > 1 ) {
dom = `${tmp[tmp.length-2]}.${tmp[tmp.length-1]}`
}
console.log( `origin: ${origin}, dom:${dom}, CORS allowed? : ${dataclient.DOMs.includes( dom )}` );
if( dataclient.DOMs.includes( dom ) ) {
callback( null, true )
} else {
console.log( `Origin is not allowed by CORS` );
callback( new Error( 'Not allowed by CORS' ) );
}
}
},
exposedHeaders: Object.keys( conf.api.exposedHeaders )
};
// CORS
app.use( cors( corsOptions ) );
// Static Routes
/*app.use( express.static( `${__dirname}/nationchains/tribes/${conf.mayorId}/www/cdn/public`, {
dotfiles: 'allow'
} ) );
*/
//Allow to public access a space dev delivered by apxtrib
// this is just a static open route for dev purpose,
// for production, we'll use a nginx static set to /www/app/appname
/*console.log( `${conf.dnsapxtrib}/space/tribeid/website`, dataclient.appname );
Object.keys( dataclient.appname )
.forEach( cid => {
dataclient.appname[ cid ].forEach( website => {
app.use( `/space/${cid}/${website}`, express.static( `${conf.tribes}/${cid}/spacedev/${website}` ) );
} )
} );
*/
// Routers add any routes from /routes and /plugins
console.log( 'Routes available on this apxtrib instance' );
console.log( routes );
// prefix only use for dev purpose in production a proxy nginx redirect /app/ to node apxtrib
routes.forEach( r => {
try {
app.use( r.url, require( r.route ) );
} catch ( err ) {
console.log( `\x1b[31m!!! WARNING issue with route ${r.route} from ${r.url} check err if route is key then solve err, if not just be aware that this route won't work on your server. If you are not the maintainer and no turn around please contact the email maintainer.\x1b[0m` )
console.log( 'raise err-:', err );
}
} )
app.listen( conf.api.port, () => {
console.log( `check in your browser that api works http://${conf.dns}:${conf.api.port}` );
} );
console.log( "\x1b[42m\x1b[37m", "Made with love for people's freedom, enjoy !!!", "\x1b[0m" );