From 61bb9bc6e2a7f4e7ca2d4430f7b99e53b0b1dc59 Mon Sep 17 00:00:00 2001
From: Kshitij Sobti <kshitij@sobti.in>
Date: Fri, 14 Jun 2019 18:01:57 +0530
Subject: [PATCH] Add support for using an authentication database for MongoDB.
 A popular convention is to have user accounts stored in a separate
 authentication database. This change add support for configuring edx-platform
 to work with such a setup.

---
 common/djangoapps/track/backends/mongodb.py | 5 ++++-
 common/lib/xmodule/xmodule/mongo_utils.py   | 6 ++++--
 2 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/common/djangoapps/track/backends/mongodb.py b/common/djangoapps/track/backends/mongodb.py
index 94453118794..6ac938658d4 100644
--- a/common/djangoapps/track/backends/mongodb.py
+++ b/common/djangoapps/track/backends/mongodb.py
@@ -29,6 +29,7 @@ class MongoBackend(BaseBackend):
           - `password`: collection user password
           - `database`: name of the database
           - `collection`: name of the collection
+          - 'auth_source': name of the authentication database
           - `extra`: parameters to pymongo.MongoClient not listed above
 
         """
@@ -46,6 +47,8 @@ class MongoBackend(BaseBackend):
         db_name = kwargs.get('database', 'track')
         collection_name = kwargs.get('collection', 'events')
 
+        auth_source = kwargs.get('auth_source') or None
+
         # Other mongo connection arguments
         extra = kwargs.get('extra', {})
 
@@ -67,7 +70,7 @@ class MongoBackend(BaseBackend):
         database = self.connection[db_name]
 
         if user or password:
-            database.authenticate(user, password)
+            database.authenticate(user, password, source=auth_source)
 
         self.collection = database[collection_name]
 
diff --git a/common/lib/xmodule/xmodule/mongo_utils.py b/common/lib/xmodule/xmodule/mongo_utils.py
index 1704f883a01..bb70697f5eb 100644
--- a/common/lib/xmodule/xmodule/mongo_utils.py
+++ b/common/lib/xmodule/xmodule/mongo_utils.py
@@ -36,6 +36,9 @@ def connect_to_mongodb(
         # No 'replicaSet' in kwargs - so no secondary reads.
         mongo_client_class = pymongo.MongoClient
 
+    # If the MongoDB server uses a separate authentication database that should be specified here
+    auth_source = kwargs.pop('auth_source', '') or None
+
     # If read_preference is given as a name of a valid ReadPreference.<NAME> constant
     # such as "SECONDARY_PREFERRED", convert it. Otherwise pass it through unchanged.
     if 'read_preference' in kwargs:
@@ -59,10 +62,9 @@ def connect_to_mongodb(
             mongo_conn,
             wait_time=retry_wait_time
         )
-
     # If credentials were provided, authenticate the user.
     if user is not None and password is not None:
-        mongo_conn.authenticate(user, password)
+        mongo_conn.authenticate(user, password, source=auth_source)
 
     return mongo_conn
 
-- 
GitLab