From c21398ad32969f2921390c4a02731421330e8c4a Mon Sep 17 00:00:00 2001 From: Rudi van Hierden Date: Tue, 23 Aug 2022 14:56:23 +0200 Subject: [PATCH 1/2] Allow MongoDB credentials to be set This commit together with https://github.com/openstad/openstad-frontend/pull/354 allows MongoDB to have authentication. This commit introduces 3 new environment variables: - MONGO_DB_USER - MONGO_DB_PASSWORD - MONGO_DB_AUTHSOURCE If both `MONGO_DB_USER` and `MONGO_DB_PASSWORD` are set, they are added to the MongoDB connection string. The `MONGO_DB_AUTHSOURCE` allows us to specify which database we are authenticating against. (see https://www.mongodb.com/docs/manual/reference/connection-string/#std-label-connections-connection-options) --- app-init.js | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/app-init.js b/app-init.js index be5627af..533132af 100644 --- a/app-init.js +++ b/app-init.js @@ -39,12 +39,19 @@ const sessionStore = new MySQLStore({ */ -const mongoCredentials = { - host: process.env.MONGO_DB_HOST || 'localhost', - port: process.env.MONGO_DB_PORT || 27017, +function getMongoDbConnectionString () { + const host = process.env.MONGO_DB_HOST || 'localhost'; + const port = process.env.MONGO_DB_PORT || 27017; + const user = process.env.MONGO_DB_USER || ''; + const password = process.env.MONGO_DB_PASSWORD || ''; + const authSource = process.env.MONGO_DB_AUTHSOURCE || ''; + + const useAuth = user && password; + + return `mongodb://${useAuth ? `${user}:${password}@` : ''}${host}:${port}/sessions${authSource ? `?authSource=${authSource}` : ''}`; } -const url = 'mongodb://'+ mongoCredentials.host +':'+mongoCredentials.port+'/sessions'; +const url = getMongoDbConnectionString(); const sessionStore = new MongoStore({ url: url, From 12b32dbf3417225348b58c0cd519555f06039478 Mon Sep 17 00:00:00 2001 From: Rudi van Hierden Date: Wed, 24 Aug 2022 10:12:16 +0200 Subject: [PATCH 2/2] Add `MONGO_DB_CONNECTION_STRING` to override the connection string builder This avoids the need of having to specify the following environment variables: `MONGO_DB_HOST`, `MONGO_DB_PORT`, `MONGO_DB_USER`, `MONGO_DB_PASSWORD` and `MONGO_DB_AUTHSOURCE` and allows greater control of the connection string. --- app-init.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app-init.js b/app-init.js index 533132af..319fa0c3 100644 --- a/app-init.js +++ b/app-init.js @@ -40,6 +40,11 @@ const sessionStore = new MySQLStore({ function getMongoDbConnectionString () { + // Allow the connection string builder to be overridden by an environment variable + if (process.env.MONGO_DB_CONNECTION_STRING) { + return process.env.MONGO_DB_CONNECTION_STRING; + } + const host = process.env.MONGO_DB_HOST || 'localhost'; const port = process.env.MONGO_DB_PORT || 27017; const user = process.env.MONGO_DB_USER || '';