From 53cbd9372ba579bb08e1e84ac23a74d7204e6c29 Mon Sep 17 00:00:00 2001 From: Ferotiq <64989416+Ferotiq@users.noreply.github.com> Date: Mon, 13 Dec 2021 10:00:09 -0600 Subject: [PATCH] Add Option to Use MongoDB Credentials (#2169) by Ferotiq * Add Option to Use MongoDB Credentials * updated example Co-authored-by: Jack --- CONTRIBUTING.md | 2 ++ backend/example.env | 8 +++++++- backend/init/mongodb.js | 21 +++++++++++++++++++-- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 01e8f742b..fc4746e36 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -83,6 +83,8 @@ Follow these steps if you want to work on anything involving the database/accoun 1. Inside the backend folder, copy `example.env` to `.env` in the same directory. + 1. If necessary, uncomment the lines in the `.env` file to use credentials to login to MongoDB. + 1. Optional - Install [MongoDB-compass](https://www.mongodb.com/try/download/compass?tck=docs_compass). This tool can be used to see and manipulate your data visually. 1. To connect, type `mongodb://localhost:27017` in the connection string box and press connect. The monkeytype database will be created and shown` after the server is started`. diff --git a/backend/example.env b/backend/example.env index aafe4e753..8c9051916 100644 --- a/backend/example.env +++ b/backend/example.env @@ -1,2 +1,8 @@ +DB_NAME=monkeytype DB_URI=mongodb://localhost:27017 -DB_NAME=monkeytype \ No newline at end of file +# You can also use the format mongodb://username:password@host:port or +# uncomment the following lines if you want to define them separately +# DB_USERNAME= +# DB_PASSWORD= +# DB_AUTH_MECHANISM="SCRAM-SHA-256" +# DB_AUTH_SOURCE=admin diff --git a/backend/init/mongodb.js b/backend/init/mongodb.js index 99ba4f613..2950ed94e 100644 --- a/backend/init/mongodb.js +++ b/backend/init/mongodb.js @@ -4,10 +4,27 @@ let mongoClient; module.exports = { async connectDB() { - return MongoClient.connect(process.env.DB_URI, { + let options = { useNewUrlParser: true, useUnifiedTopology: true, - }) + }; + + if (process.env.DB_USERNAME && process.env.DB_PASSWORD) { + options.auth = { + username: process.env.DB_USERNAME, + password: process.env.DB_PASSWORD, + }; + } + + if (process.env.DB_AUTH_MECHANISM) { + options.authMechanism = process.env.DB_AUTH_MECHANISM; + } + + if (process.env.DB_AUTH_SOURCE) { + options.authSource = process.env.DB_AUTH_SOURCE; + } + + return MongoClient.connect(process.env.DB_URI, options) .then((client) => { mongoClient = client; })