Skip to content

Commit

Permalink
Merge pull request #497 from timeoff-management/tom-xxx-redis-as-sess…
Browse files Browse the repository at this point in the history
…ion-store

Introduce Redis as alternative session storage.
  • Loading branch information
vpp authored Oct 19, 2021
2 parents df738ee + cf37823 commit fcbcb8d
Show file tree
Hide file tree
Showing 7 changed files with 130 additions and 19 deletions.
13 changes: 3 additions & 10 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var moment = require('moment');
const createSessionMiddleware = require('./lib/middleware/withSession');

var app = express();

Expand Down Expand Up @@ -37,16 +38,8 @@ app.use(express.static(path.join(__dirname, 'public')));
// Setup authentication mechanism
const passport = require('./lib/passport')();

var session = require('express-session');
// Initialize sequelize with session store
var SequelizeStore = require('connect-session-sequelize')(session.Store);
app.use(session({
secret : 'my dirty secret ;khjsdkjahsdajhasdam,nnsnad,',
resave : false,
saveUninitialized : false,
store: new SequelizeStore({
db: app.get('db_model').sequelize
}),
app.use(createSessionMiddleware({
sequelizeDb: app.get('db_model').sequelize,
}))
app.use(passport.initialize());
app.use(passport.session());
Expand Down
7 changes: 7 additions & 0 deletions config/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@
"pass" : "pass"
}
},
"sessionStore": {
"useRedis": false,
"redisConnectionConfiguration": {
"host": "localhost",
"port": 6379
}
},
"ga_analytics_on" : false,
"crypto_secret" : "!2~`HswpPPLa22+=±§sdq qwe,appp qwwokDF_",
"application_domain" : "http://app.timeoff.management",
Expand Down
2 changes: 1 addition & 1 deletion config/db.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"development": {
"dialect": "sqlite",
"storage": "./db.development.sqlite",
"logging": false
"logging": false
},
"test": {
"username": "root",
Expand Down
15 changes: 15 additions & 0 deletions docs/SessionStoreInRedis.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# How to use Redis as storage for Sessions

By default application uses its database as a storage for session data (`Sessions` table).

It is possible to use different storage mechanism for Sessions data: [Redis](https://redis.io/).

## Steps

* Ensure the application's source is at least `1.4.0`
* Stop the application
* Open `config/app.json` for editing
* Update `sessionStore.useRedis` section to be `true`
* Update `sessionStore.redisConnectionConfiguration`'s `host` and `port` pointing to corresponding instance of Redis
* Save the configuration file
* Restart the application
47 changes: 47 additions & 0 deletions lib/middleware/withSession.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@

const session = require('express-session');
const SequelizeStore = require('connect-session-sequelize')(session.Store);

const redis = require('redis');
const connectRedis = require('connect-redis');

const {sessionStore: sessionStoreConfig} = require(__dirname + '/../../config/app.json') || {};

const createSessionMiddleware = ({
sequelizeDb,
}) => {
let store;

if (sessionStoreConfig && sessionStoreConfig.useRedis) {
const RedisStore = connectRedis(session);
const {redisConnectionConfiguration = {}} = sessionStoreConfig;
const {host, port} = redisConnectionConfiguration;
if (!(host && port)) {
throw new Error('Missing configuration for Redis to use with Sessions');
}
const redisClient = redis.createClient({ host, port });

redisClient.on('error', function (err) {
throw new Error(`Failed to connect to Redis: ${err}`);
});
redisClient.on('connect', function (err) {
console.log('Connected to redis successfully');
});

store = new RedisStore({ client: redisClient });
} else {
if (!sequelizeDb) {
throw new Error('Database connection was not provided into Session store manager!');
}
store = new SequelizeStore({ db: sequelizeDb });
}

return session({
store,
secret: 'my dirty secret ;khjsdkjahsdajhasdam,nnsnad,',
resave: false,
saveUninitialized: false,
});
};

module.exports = createSessionMiddleware;
63 changes: 55 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"dependencies": {
"bluebird": "^2.10.2",
"body-parser": "^1.8.4",
"connect-redis": "^6.0.0",
"connect-session-sequelize": "3.0.0",
"cookie-parser": "^1.3.5",
"csv": "~0.4.6",
Expand All @@ -33,6 +34,7 @@
"passport": "^0.3.2",
"passport-http-bearer": "^1.0.1",
"passport-local": "^1.0.0",
"redis": "^3.1.2",
"sequelize": "^3.19.2",
"sequelize-cli": "2.5.1",
"serve-favicon": "^2.1.7",
Expand Down

0 comments on commit fcbcb8d

Please sign in to comment.