1
0
Fork 0

web - persistent sessions using mongodb as session-store

This commit is contained in:
Ruben Meyer 2020-08-17 13:57:10 +02:00
parent 73df853124
commit dcbe7509d2
Signed by: rxbn_
GPG Key ID: BE3BF898BE352FE2
6 changed files with 51 additions and 19 deletions

View File

@ -5,11 +5,11 @@ Single sign-on authentication and authorization service for rxbn.de services
# start server # start server
## normal start ## normal start
```sh ```sh
$ DB_URL=mongodb://user:pass@ip:port/authdb DB_NAME=authRxbn node app.js $ DB_URL="mongodb://user:pass@ip:port/authdb" DB_NAME="authRxbn" SESSION_KEY="32byteHexString" COOKIE_KEY="32byteHexString" node app.js
``` ```
## debug start (with debug output/logs) ## debug start (with debug output/logs)
```sh ```sh
$ DB_URL=mongodb://user:pass@ip:port/authdb DB_NAME=authRxbn NODE_ENV=debug node app.js $ DB_URL="mongodb://user:pass@ip:port/authdb" DB_NAME="authRxbn" SESSION_KEY="32byteHexString" COOKIE_KEY="32byteHexString" NODE_ENV=debug node app.js
``` ```
# TODO # TODO

2
app.js
View File

@ -21,7 +21,7 @@ let load = global['requireModule'] = (name) => {
}; };
// environment variable check // environment variable check
let env_vars = ["DB_URL", "DB_NAME"]; let env_vars = ["DB_URL", "DB_NAME", "SESSION_KEY", "COOKIE_KEY"];
let env_missing = false; let env_missing = false;
env_vars.forEach((el) => { env_vars.forEach((el) => {
if(typeof process.env[el] == 'undefined') { if(typeof process.env[el] == 'undefined') {

View File

@ -20,8 +20,8 @@ module.exports = {
host: "auth.rxbn.de", host: "auth.rxbn.de",
port: 8080, port: 8080,
poweredBy: 'authRXBN.js', poweredBy: 'authRXBN.js',
sessionKey: require('crypto').randomBytes(32).toString('hex'), sessionKey: process.env.SESSION_KEY,
cookieKey: require('crypto').randomBytes(32).toString('hex'), cookieKey: process.env.COOKIE_KEY,
registration: false, // false -> no registration registration: false, // false -> no registration
cookieMaxAge: 1000*60*60 // one hour (milliseconds*seconds*minutes) cookieMaxAge: 1000*60*60 // one hour (milliseconds*seconds*minutes)
}, },

View File

@ -48,6 +48,15 @@ methods.connect = async () => {
}); });
} }
/**
* returns db instance
* @author Ruben Meyer
* @return {Object} mongoose
*/
methods.getConnection = () => {
return db;
}
// // // //////// //////// /////// // // // //////// //////// ///////
// // // // // // // // // // // // // //
// // // ////// ////// ////// // // // ////// ////// //////

View File

@ -18,6 +18,7 @@ methods.start = () => {
// init express framework // init express framework
let express = require('express'); let express = require('express');
let session_handler = require('express-session'); let session_handler = require('express-session');
let session_store = require('connect-mongo')(session_handler);
// utilities // utilities
let fs = require('fs'); let fs = require('fs');
@ -86,18 +87,34 @@ methods.start = () => {
if(app.get('env') === 'debug') if(app.get('env') === 'debug')
app.locals.pretty = true; app.locals.pretty = true;
// Sessions
session_options = {
secret: cfg.web.sessionKey,
resave: false,
saveUninitialized: false, cookie: {}};
if(app.get('env') === 'production') {
session_options.cookie.secure = true;
}
app.use(session_handler(session_options));
// web routes
(async function() { (async function() {
// mongooseConnection
let db = global['requireModule']('database');
await db.connect();
let con = db.getConnection();
// Sessions
session_options = {
secret: cfg.web.sessionKey,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: cfg.web.cookieMaxAge
},
store: new session_store({
mongooseConnection: con,
dbName: cfg.mongoose.db,
ttl: cfg.web.cookieMaxAge,
secret: (app.get('env') === 'production') ? true : false
})
};
if(app.get('env') === 'production') {
app.set('trust proxy', 1);
session_options.cookie.secure = true;
}
app.use(session_handler(session_options));
// web routes
let mRoutes = require(global['__dirname']+'/bin/web/routes/static'); let mRoutes = require(global['__dirname']+'/bin/web/routes/static');
let mainRoutes = await mRoutes.getRoutes(); let mainRoutes = await mRoutes.getRoutes();
app.use('/', mainRoutes); app.use('/', mainRoutes);
@ -106,9 +123,14 @@ methods.start = () => {
app.use('/api', restAPI); app.use('/api', restAPI);
// start server // start server
app.listen(cfg.web.port, () => { if(app.get('env') === 'production' && cfg.web.host && typeof cfg.web.host == "string")
global['logs'].log("Server is listening on port: "+cfg.web.port); app.listen(cfg.web.port, cfg.web.host, () => {
}); global['logs'].log("Server is listening on port: "+cfg.web.port);
});
else if(app.get('env') === 'debug' || !cfg.web.host || typeof cfg.web.host !== "string")
app.listen(cfg.web.port, () => {
global['logs'].log("Server is listening on port: "+cfg.web.port);
});
})(); })();
}; };

View File

@ -7,6 +7,7 @@
"license": "", "license": "",
"dependencies": { "dependencies": {
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
"connect-mongo": "^3.2.0",
"cookie-parser": "^1.4.5", "cookie-parser": "^1.4.5",
"express": "^4.17.1", "express": "^4.17.1",
"express-async-handler": "^1.1.4", "express-async-handler": "^1.1.4",