繁体   English   中英

mongodb python 获取数据库用户

[英]mongodb python get users of database

我想创建一个管理应用程序来监控数据收集。 为此,用户注册过程基于数据库访问,即,当我们通过 MongoDB 地图集创建新的数据库用户时,他们将立即能够使用其数据库用户名和密码登录到管理应用程序。 如何使用 python 获取包含数据库用户列表及其散列密码的 mongo 文档/响应?

我制作了一个 function,它接受 Mongo 数据库用户的用户名和密码,并使用它连接到 Mongo 客户端。 然后我尝试执行基本的读取操作(读取操作需要最少的用户权限)如果读取操作成功,则表示提供的用户名和密码是真实的,我返回 true,否则检查操作是否由于身份验证失败而失败并返回假。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM