我正在为firebase的云firestore编写规则,我想使用用户的auth id限制对数据库的访问,但规则的行为并不像我预期的那样。
所以,我的数据库结构是这样的:
/users/{userId}/groups/{groupId}
我希望只有用户才能使用他们自己的userId访问文档。
为了实现这一点,我编写了如下规则:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId=**} {
allow read: if userId == request.auth.uid;
}
}
}但是这样,我的用户就不能从数据库中读取他们自己的“组”。
我使用的是javascript,检索“group”的代码如下:
console.log("uid: ", uid)
db.collection("users/" + uid + "/groups")
.onSnapshot(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.data())
})
})现在,由于云firestore没有像实时数据库这样好的调试工具,所以我自己做了一些调试。
我有一个测试用户的uid是“5lS2NA21UpbabEw4AkyWyef9FH42”,所以我像这样修改了规则:
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;
}
}
}现在我无法从数据库中获得任何数据。
谁能告诉我我哪里做错了?
发布于 2017-12-18 02:56:50
我想我已经弄明白了。问题是{userId=**}
如果你有以下规则
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId=**} {
allow read: if userId == request.auth.uid;
}
}
}并试图访问users/5lS2NA21UGABEw4AkyWyef9FH42/groups,"userId“变量不会计算为5lS2NA21UGABEw4AkyWyef9FH42(我不知道它会是什么,但我会猜”5lS2NA21UGBAEw4AkyWyef9FH42/groups“)。因此,如果要将文档私有化,则必须在规则中指定每个文档,如下所示。
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;
}
}
}
}https://stackoverflow.com/questions/47856426
复制相似问题