Reputation: 37
I want to create an admin application to monitor data collection. For this the user registration process is based on the database access i.e, when we create a new database user through MongoDB atlas, they will immediately be able to log into the admin application with their database username and password. How do I get a mongo document/response containing the list of database users and their hashed passwords using python?
Upvotes: 0
Views: 996
Reputation: 37
I made a function that accepts the Mongo database user's username and password and uses that to connect to a Mongo client. I then attempt to perform a basic read operation (read operation requires the least user privilege) If the read op is successful then it means the username and password provides are authentic and I return true, else check if the operation failed because of a failed authentication and return false.
from pymongo import MongoClient
from pymongo.errors import OperationFailure
def check_dbuser(username, password):
""" Attempts to connect to mongo atlas using the username and password. It then attempts a basic operation which is
to list the database names of the cluster. If the operation works, the username and password are authentic and
return True.
Else if there is an OperationFailure we check that the error is due to failed authentication and return False
"""
auth = False
failed_message = 'bad auth Authentication failed.' # this is the err message returned on a failed authentication
uri = f'mongodb+srv://{username}:{password}@cluster-connection-string'
client = MongoClient(uri)
try:
client.list_database_names()
except OperationFailure as e:
assert(e.details['errmsg'] == failed_message) # assert that the error message is that of an authentication failure
else:
auth = True
return auth
Upvotes: 0