1
0
Fork 0
SSObaseApp_nodeJS/bin/web/module.js

139 lines
3.7 KiB
JavaScript

// init
var methods = {};
/**
* start web server
* @author Ruben Meyer
* @return {Void}
*/
methods.start = () => {
// init express framework
let express = require('express');
let session_handler = require('express-session');
// utilities
let fs = require('fs');
let path = require('path');
let mime = require('mime-types');
// app variable
let app = express();
app.set('view engine', 'pug'); // page engine
app.set('views', global['__dirname']+'/bin/web');
let bp = require('body-parser'); // POST Body parser
let cp = require('cookie-parser'); // Cookie handler
// Access Control Headers
app.use( (req, res, next) => {
res.set({
'X-Powered-By': global['gds'].cfg
});
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// BodyParser & CookieParser
app.use(bp.json());
app.use(bp.urlencoded({
extended: true
}));
app.use(cp(global['gds'].cfg.web.cookieKey));
// Pretty print
app.locals.pretty = true;
// Sessions
session_options = {
secret: global['gds'].cfg.web.sessionKey,
resave: false,
saveUninitialized: false, cookie: {}};
if(app.get('env') === 'production') {
session_options.cookie.secure = true;
}
app.use(session_handler(session_options));
//static files
app.use('/res', (req, res, next) => {
if(typeof global['gds'].cache.web == 'undefined') global['gds'].cache.web = {};
let dir = global['__dirname'] + '/res/web';
if(!req.session || !req.session.user) dir += '/auth';
else dir += '/app';
let joined_path = path.join(dir, /^[^?]+/.exec(req.url)[0]);
// path already cached; not exist
if(global['gds'].cache.web[joined_path] == false) {
res.status(404).end();
// path already cached; exist
} else if(global['gds'].cache.web[joined_path] == true){
let contentType = mime.contentType(path.extname(joined_path));
res.setHeader('Content-Type', contentType);
fs.createReadStream(joined_path).pipe(res);
// check path
} else {
fs.exists(joined_path, (exists) => {
global['gds'].cache.web[joined_path] = exists;
if(exists) {
let contentType = mime.contentType(path.extname(joined_path));
res.setHeader('Content-Type', contentType);
fs.createReadStream(joined_path).pipe(res);
} else {
res.status(404).end();
}
});
}
});
// web routes
app.use('/auth', require(global['__dirname']+'/bin/web/auth/routes/main'));
app.use('/', require(global['__dirname']+'/bin/web/app/routes/main'));
// start server
app.listen(global['gds'].cfg.web.port, () => {
global['modules'].logs.log("Server is listening on port: "+global['gds'].cfg.web.port);
});
// DEBUG OUTPUT: list all routes with HTTP method
setTimeout(function () {
function print (path, layer) {
if (layer.route) {
layer.route.stack.forEach(print.bind(null, path.concat(split(layer.route.path))))
} else if (layer.name === 'router' && layer.handle.stack) {
layer.handle.stack.forEach(print.bind(null, path.concat(split(layer.regexp))))
} else if (layer.method) {
console.log('%s /%s',
layer.method.toUpperCase(),
path.concat(split(layer.regexp)).filter(Boolean).join('/')
);
}
}
function split (thing) {
if (typeof thing === 'string') {
return thing.split('/')
} else if (thing.fast_slash) {
return ''
} else {
var match = thing.toString()
.replace('\\/?', '')
.replace('(?=\\/|$)', '$')
.match(/^\/\^((?:\\[.*+?^${}()|[\]\\\/]|[^.*+?^${}()|[\]\\\/])*)\$\//)
return match
? match[1].replace(/\\(.)/g, '$1').split('/')
: '<complex:' + thing.toString() + '>'
}
}
app._router.stack.forEach(print.bind(null, []))
}, 1500);
};
module.exports = methods;