为了满足要求,“在不授予对整个用户集合的访问权限的情况下,查询数据库中是否存在具有特定电子邮件的用户,”您需要重新考虑您的数据库架构。 Firestore 不允许您对您没有读取权限的数据进行查询。
我建议创建一个单独的集合,其中仅包含正在使用的电子邮件地址,如下所示:
{
"emails": {
"jane@example.com": { userId: "abc123" },
"sally@example.com": { userId: "xyz987" },
"joe@example.com": { userId: "lmn456" }
}
}
每次添加用户或更改电子邮件地址时都应更新此集合。
然后像这样设置您的 Firestore 规则:
service cloud.firestore {
match /databases/{database}/documents {
match /emails/{email} {
// Allow world-readable access if the email is guessed
allow get: if true;
// Prevent anyone from getting a list of emails
allow list: if false;
}
}
}
有了所有这些,您就可以安全地允许匿名查询以检查电子邮件是否存在,而无需打开您的和服,可以这么说。
列出所有电子邮件
firebase.firestore().collection('emails').get()
.then((results) => console.error("Email listing succeeded!"))
.catch((error) => console.log("Permission denied, your emails are safe."));
Result: "Permission denied, your emails are safe."
检查 joe@example.com 是否存在
firebase.firestore().collection('emails').doc('joe@example.com').get()
.then((node) => console.log({id: node.id, ...node.data()}))
.catch((error) => console.error(error));
Result: {"id": "joe@example.com": userId: "lmn456"}
检查 sam@example.com 是否存在
firebase.firestore().collection('emails').doc('sam@example.com').get()
.then((node) => console.log("sam@example.com exists!"))
.catch((error) => console.log("sam@example.com not found!"));
Result: sam@example.com not found!