如何使用 PyMongo 对 Python 桌面应用程序进行数据库用户身份验证

问题描述 投票:0回答:1

我不确定我是否只是找错了地方,或者可能没有完全理解这些概念(可能是这样),但我希望我能在这个问题上得到一些帮助。

我有一个与 MongoDB 交互的桌面 Python 应用程序,以以下形式将数据存储在集合中:

Account = {
"account": username,
"password": hashed_password,
"data": [],
}

目前,当用户登录时,哈希输入会与数据库中的哈希密码进行检查,以查看其是否正确。只有这样,他们才能够访问数据=[]。但是,我找不到合适的方法来在 Python 中处理此身份验证。我发现 MongoDB Realms API 具有身份验证服务和规则服务,但我不确定如何将其与 PyMongo 和纯桌面 Python 应用程序混合。

此外,我的Python程序代码是公开的,因此(理论上)我想确保人们无法通过更改我的程序代码直接访问其他帐户数据。

我推测问题在于我尝试使用 MongoDB/PyMongo 而不是其他数据库。也许 MongoDB 是为了与 Web 应用程序一起使用而设计的,而不是与桌面应用程序一起使用。

目前我真正能想到的唯一解决方案是通过以下方式访问数据:

collection.find_one({"password": hashed_password})

我相当确定这是一个安全风险。

因此,有没有一种方法可以仅使用 PyMongo 对用户进行身份验证,以便他们只能访问用户集合中自己的用户数据?或者我会使用请求和 MongoDB 的 App API 来自定义权限吗?

python mongodb pymongo
1个回答
0
投票

事实证明,我可以创建一个 MongoDB Atlas 函数和触发器,它接受用户名和密码(密码应该已经经过哈希处理)。在该函数中,我迭代集合内容并查看密码是否匹配。如果是这样,我返回数据。

exports = async function(username, password) {
  const accountsCollection = context.services
    .get("service-name")
    .db("db-name")
    .collection("collection-name");

  const account = await accountsCollection.findOne({ account: username });

  if (account && account.password === password) {
    return account.data;
  } else {
    throw new Error("Invalid username or password.");
  }
};

在我的 python 文件中,我不使用 PyMongo。相反,我使用 requests 来调用请求。

import requests

# Replace with your MongoDB Realm trigger URL
trigger_url = "https://your-realm-app.mongodbstitch.com/api/client/v2.0/app/your-app-id/service/your-service-id/incoming_webhook/getAccountData"

# Replace with the actual username and password
username = "test"
password = "test"

# Make an HTTP GET request to invoke the function
response = requests.get(trigger_url, params={"username": username, "password": password})

这样,我就不必在本地处理密码验证了。

© www.soinside.com 2019 - 2024. All rights reserved.