Compare commits

...

7 Commits

  1. 24
      app.js
  2. 9
      bin/config.js
  3. 21
      bin/logs/module.js
  4. 54
      bin/sso/module.js
  5. 14
      bin/web/app/routes/main.js
  6. 31
      bin/web/auth/routes/api.js
  7. 5
      bin/web/auth/routes/static.js
  8. 2
      bin/web/auth/views/index.pug
  9. 82
      bin/web/module.js
  10. 8
      package.json

24
app.js

@ -1,22 +1,15 @@
// GDS: Global Data System
global['gds'] = {
debug: (process.env.NODE_ENV === 'debug') ? true : false,
db: null,
cache: {},
cfg: require(__dirname+'/bin/config')
};
global['modules'] = {};
global['debug'] = (process.env.NODE_ENV === 'debug') ? true : false;
global['__dirname'] = __dirname;
/**
* load modules
*/
let load = (name) => {
const load = (name) => {
return require(__dirname+'/bin/'+name+'/module');
};
// environment variable check
let env_vars = ["APP_ID", "APP_SECRET"];
const env_vars = ["APP_ID", "APP_SECRET"];
let env_missing = false;
env_vars.forEach((el) => {
if(typeof process.env[el] == 'undefined') {
@ -26,14 +19,9 @@ env_vars.forEach((el) => {
});
if(env_missing) process.exit();
global['modules'].logs = load('logs'); // log handler
global['logs'] = global['modules'].logs; // alias
global['modules'].web = load('web'); // web server
global['modules'].sso = load('sso'); // sso service
// custom modules
global['logs'] = load('logs'); // log handler
const webServer = load('web'); // web server
// start web server
global['modules'].web.start();
webServer.start();

9
bin/config.js

@ -9,17 +9,18 @@ module.exports = {
},
web: {
host: "*",
port: 8080,
port: 8081,
poweredBy: 'baseApp',
rootUrl: '/', // '/', '/SSObaseApp'
rootUrl: '/', // '/', '/SSObaseApp/'
doubleSlashCheck: true, // replacing // with /
sessionKey: require('crypto').randomBytes(32).toString('hex'),
cookieKey: require('crypto').randomBytes(32).toString('hex'),
rememberMeMaxAge: 1000*60*60 // two weeks (milliseconds*seconds*minutes)
},
sso: {
authenticator: "http://localhost:8080/api/authenticate", // redirect back to this url;
provider: "https://auth.rxbn.de/authenticate", // sso service
authenticator: "http://localhost:8081/api/authenticate", // redirect back to this url;
providerApi: "http://localhost:8080/api/authenticate", // sso service api
providerUI: "http://localhost:8080/authenticate", // sso service
appId: process.env.APP_ID, // app id
appSecret: process.env.APP_SECRET // random token
},

21
bin/logs/module.js

@ -2,12 +2,13 @@ var methods = {};
let fs = require('fs');
let util = require('util');
var cfg = require(global['__dirname']+'/bin/config');
// save new line to file
newLine = (prefix, obj) => {
let date = new Date(); // current date
let filename = global['gds'].cfg.log.filename(); // filename
let dir = global['gds'].cfg.log.directory(); // directory
let filename = cfg.log.filename(); // filename
let dir = cfg.log.directory(); // directory
let path = dir + filename; // filepath
let fs_options = { // fs options for encoding, file mode and file flag
encoding: "utf8",
@ -46,7 +47,7 @@ newLine = (prefix, obj) => {
}
};
fallback = (fn, ...data) => {
log = (fn, ...data) => {
if(data.length == 1) data = data[0];
fn.apply(null, data);
@ -55,8 +56,7 @@ fallback = (fn, ...data) => {
// LOG | INFO
methods.log = (...data) => {
if(global['modules'].cli) global['modules'].cli.log.apply(global['modules'].cli, data);
else fallback(console.log, data);
log(console.log, data);
if(data.length == 1) data = data[0];
newLine(" [LOG]", data);
@ -65,8 +65,7 @@ methods.info = methods.log;
// WARNING
methods.warn = (...data) => {
if(global['modules'].cli) global['modules'].cli.log.apply(global['modules'].cli, data);
else fallback(console.warn, data);
log(console.warn, data);
if(data.length == 1) data = data[0];
newLine(" [WARN]", data);
@ -74,8 +73,7 @@ methods.warn = (...data) => {
// ERROR
methods.error = (...data) => {
if(global['modules'].cli) global['modules'].cli.log.apply(global['modules'].cli, data);
else fallback(console.error, data);
log(console.error, data);
if(data.length == 1) data = data[0];
newLine("[ERROR]", data);
@ -84,9 +82,8 @@ methods.err = methods.error;
// DEBUG
methods.debug = (...data) => {
if(global['gds'].debug) {
if(global['modules'].cli) global['modules'].cli.log.apply(global['modules'].cli, data);
else fallback(console.log, data);
if(global['debug'] === true) {
log(console.log, data);
if(data.length == 1) data = data[0];
newLine("[DEBUG]", data);

54
bin/sso/module.js

@ -6,42 +6,38 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var functions = {};
var request = require('request');
var querystring = require('querystring');
const methods = {};
const bent = require('bent');
const querystring = require('querystring');
const cfg = require(global['__dirname']+'/bin/config');
/**
* authenticate user
* @author Ruben Meyer
* @param {Object} obj obj (userId, userToken, appId, appSecret)
* @param {Function} callback obj (err, access => true, false)
* @async
* @param {Object} obj obj (userId, token, appId, appSecret)
* @return {Object} callback obj (err, access => {true, false})
*/
functions.authenticateUser = (obj, callback) => {
if(typeof callback !== 'function') callback = function() {};
methods.authenticateUser = async (obj, callback) => {
let request = bent(cfg.sso.providerApi, 'POST', 'json', 200);
request({
method: 'POST',
uri: global['gds'].cfg.sso.provider,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
try {
let post = await request('', {
applicationId: obj.appId,
applicationSecret: obj.appSecret,
userId: obj.userId,
token: obj.userToken
})
}, (err, res, body) => {
console.log('error:', err); // Print the error if one occurred
console.log('statusCode:', res && res.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML
try {
if(typeof body !== "object") body = JSON.parse(body);
return callback(err, body.access);
} catch(e) {
callback(new Error("Body is misformed"));
}
});
token: obj.token
});
if(post.status == 200 && post.message == "msg.auth.authentication.successful")
return true;
} catch(err) {
// something went wrong
console.log(err);
return false;
}
};
/**
@ -51,12 +47,12 @@ functions.authenticateUser = (obj, callback) => {
* @param {Object} obj obj(url, appId)
* @param {Function} callback string(url)
*/
functions.createAuthentication = (obj) => {
methods.createAuthentication = (obj) => {
let nUrl = {
redirectUrl: obj.url,
appId: obj.appId
};
return global['gds'].cfg.sso.provider+"?"+querystring.stringify(nUrl);
return cfg.sso.providerUI+"?"+querystring.stringify(nUrl);
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

14
bin/web/app/routes/main.js

@ -1,19 +1,27 @@
var express = require('express');
var route = express.Router();
const cfg = require(global['__dirname']+'/bin/config');
route.use((req, res, next) => {
if(!req.session || !req.session.user) {
if(!req.path.startsWith('/api')) {
let path = (global['gds'].cfg.web.rootUrl+'/auth');
let path = (cfg.web.rootUrl+'/auth');
if(global['gds'].cfg.web.doubleSlashCheck) path = path.replace(/\/+/g, "/");
if(cfg.web.doubleSlashCheck) path = path.replace(/\/+/g, "/");
res.redirect(path);
} else {
res.redirect('/auth'+req.path);
}
} else next();
} else {
// initialize User
if(req.session.user.initializeUser) {
// do it
req.session.user.initializeUser = false;
}
next();
}
});
route.get('/', (req, res) => {

31
bin/web/auth/routes/api.js

@ -1,18 +1,35 @@
var express = require('express');
var route = express.Router();
const cfg = require(global['__dirname']+'/bin/config');
const sso = require(global['__dirname']+'/bin/sso/module');
route.get('/login', (req, res) => {
// TODO: login
let a = global['modules'].sso.createAuthentication({
url: global['gds'].cfg.sso.authenticator,
appId: global['gds'].cfg.sso.appId
let a = sso.createAuthentication({
url: cfg.sso.authenticator,
appId: cfg.sso.appId
});
res.redirect(a);
});
route.get('/authenticate', (req, res) => {
// TODO: authenticate
res.end();
route.get('/authenticate', async (req, res) => {
if(req.query && req.query.uid && req.query.token) {
let auth = await sso.authenticateUser({
userId: req.query.uid,
token: req.query.token,
appId: cfg.sso.appId,
appSecret: cfg.sso.appSecret
});
if(auth) {
req.session.user = {
ssoId: req.query.uid,
initializeUser: true
};
return res.redirect(cfg.web.rootUrl);
}
else return res.redirect(cfg.web.rootUrl + 'auth/login');
}
});
route.get('/logout', (req, res) => {
@ -31,7 +48,7 @@ route.get('/logout', (req, res) => {
}
});
if(global['gds'].debug) {
if(global['debug']) {
// DEBUG info
route.get('/info', (req, res) => {
let obj = {};

5
bin/web/auth/routes/static.js

@ -1,6 +1,7 @@
var express = require('express');
var route = express.Router();
const cfg = require(global['__dirname']+'/bin/config');
route.all('/', function(req, res, next) {
// TODO: show login page or dashboard
@ -17,7 +18,9 @@ route.all('/*', (req, res, next) => {
// TODO: role-based authorization
// TODO: show login page or page
res.end('500 - LEL');
res.render('auth/views/index', {
appName: cfg.app.name
});
});
module.exports = route;

2
bin/web/auth/views/index.pug

@ -1,5 +1,5 @@
//- variables
- var appName = global['gds'].cfg.app.name || "SSObaseApp";
- var appName = appName || "SSObaseApp";
- var title = "Dashboard";
mixin navItem(name, id, symbol, href)

82
bin/web/module.js

@ -1,5 +1,7 @@
// init
var methods = {};
const methods = {};
const cfg = require(global['__dirname']+'/bin/config');
/**
* start web server
@ -27,7 +29,7 @@ methods.start = () => {
// Access Control Headers
app.use( (req, res, next) => {
res.set({
'X-Powered-By': global['gds'].cfg
'X-Powered-By': cfg.web.poweredBy
});
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
@ -39,14 +41,14 @@ methods.start = () => {
app.use(bp.urlencoded({
extended: true
}));
app.use(cp(global['gds'].cfg.web.cookieKey));
app.use(cp(cfg.web.cookieKey));
// Pretty print
app.locals.pretty = true;
// Sessions
session_options = {
secret: global['gds'].cfg.web.sessionKey,
secret: cfg.web.sessionKey,
resave: false,
saveUninitialized: false, cookie: {}};
if(app.get('env') === 'production') {
@ -56,8 +58,6 @@ methods.start = () => {
//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';
@ -65,29 +65,16 @@ methods.start = () => {
else dir += '/app';
let joined_path = path.join(dir, /^[^?]+/.exec(req.url)[0]);
fs.exists(joined_path, (exists) => {
if(exists) {
let contentType = mime.contentType(path.extname(joined_path));
res.setHeader('Content-Type', contentType);
// 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();
}
});
}
fs.createReadStream(joined_path).pipe(res);
} else {
res.status(404).end();
}
});
});
// web routes
@ -95,44 +82,9 @@ methods.start = () => {
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);
app.listen(cfg.web.port, () => {
global['logs'].log("Server is listening on port: "+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;

8
package.json

@ -6,11 +6,11 @@
"author": "rxbn_",
"license": "",
"dependencies": {
"bent": "^7.3.10",
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.4",
"cookie-parser": "^1.4.5",
"express": "^4.17.1",
"express-session": "^1.16.2",
"pug": "^2.0.4",
"request": "^2.88.0"
"express-session": "^1.17.1",
"pug": "^3.0.0"
}
}

Loading…
Cancel
Save