我正在为 firebase 的 cloud firestore 编写规则,并且我想使用用户的身份验证 ID 限制对数据库的访问,但规则的行为并不符合我的预期。
所以,我的数据库结构是这样的:
/users/{userId}/groups/{groupId}
我只希望用户只能使用自己的 userId 访问文档。
为了实现这一目标,我编写了如下规则:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId=**} {
allow read: if userId == request.auth.uid;
}
}
}
但是这样,我的用户无法从数据库中读取他们自己的“组”。
我使用的是 javascript,检索“组”的代码如下:
console.log("uid: ", uid)
db.collection("users/" + uid + "/groups")
.onSnapshot(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.data())
})
})
现在由于cloud firestore没有像实时数据库那样很好的调试工具,所以我自己做了一些调试。
我有一个测试用户,uid 为“5lS2NA21UgbabEw4AkyWyef9FH42”,所以我更改了如下规则:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId=**} {
allow read: if "5lS2NA21UgbabEw4AkyWyef9FH42" == request.auth.uid;
}
}
}
这样,我的测试用户就能够从他的文档中成功检索“组”数据(当然所有其他用户都不能,但是)。
现在我将规则更改为:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId=**} {
allow read: if "5lS2NA21UgbabEw4AkyWyef9FH42" == userId;
}
}
}
现在我无法从数据库中获取任何数据。
有人可以告诉我我做错了什么吗?
最佳答案
我想我已经明白了这一点。问题是这个 {userId=**}
如果你有以下规则
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId=**} {
allow read: if userId == request.auth.uid;
}
}
}
并且正在尝试访问 users/5lS2NA21UgbabEw4AkyWyef9FH42/groups,“userId”变量的计算结果不为 5lS2NA21UgbabEw4AkyWyef9FH42 (我不知道它会是什么,但我猜测“5lS2NA21UgbabEw4AkyWyef9FH42/groups”)。因此,如果您想将文档私有(private)化,则必须在规则中指定每个文档,如下所示。
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
match /groups/{groupId} {
allow read: if userId == request.auth.uid;
}
match /events/{eventId} {
allow read: if userId == request.auth.uid;
}
}
}
}
关于javascript - 使用规则和身份验证将云 Firestore 数据库私有(private)化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47856426/