【问题标题】:mongodb python get users of databasemongodb python 获取数据库的用户
【发布时间】:2020-05-10 05:03:58
【问题描述】:

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

【问题讨论】:

  • 欢迎来到 Stackoverflow,到目前为止你尝试过什么?
  • @ngShravil.py 我联系了 MongoDB 支持,但他们说免费支持层不共享代码。
  • 您是否尝试过为此使用 Atlas API?
  • @Joe atlas API?我该如何使用它?
  • 用户存储在admin数据库的system.users集合中

标签: python mongodb pymongo


【解决方案1】:

我创建了一个函数,它接受 Mongo 数据库用户的用户名和密码,并使用它连接到 Mongo 客户端。然后我尝试执行基本的读取操作(读取操作需要最少的用户权限)如果读取操作成功,则意味着提供的用户名和密码是真实的,我返回 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

【讨论】:

  • 但是,这不是一个完整的解决方案。我仍然需要实现一个继承 UserMixins 的用户类并实现 @user_loader 这两者都需要我访问 mongodb atlas 用户数据库以进行会话管理。
  • 我已经通过创建用户缓存来满足对 UserMixins 的需求
猜你喜欢
  • 2019-02-25
  • 1970-01-01
  • 2018-09-03
  • 2021-01-20
  • 2020-04-22
  • 2023-03-24
  • 2016-06-11
  • 2020-08-13
  • 2011-06-09
相关资源
最近更新 更多