Я создал функцию, которая принимает имя пользователя и пароль пользователя базы данных Mon go и использует их для подключения к клиенту Mon go. Затем я пытаюсь выполнить базовую операцию чтения c (операция чтения требует минимальных прав пользователя). Если операция чтения прошла успешно, это означает, что предоставленные имя пользователя и пароль - authenti c, и я возвращаю true, иначе проверяю, выполняется ли операция не удалось из-за неудачной аутентификации и вернуть 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