我正在为firebase的cloud firestore编写规则,我想使用用户的auth id来限制对数据库的访问,但规则并不像我期望的那样。
所以,我的数据库结构是这样的:
/用户/ {用户id} /组/ {}的groupId
我只希望用户只能使用自己的userId访问文档。
为此,我编写了如下规则:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId=**} {
allow read: if userId == request.auth.uid;
}
}
}
但有了这个,我的用户无法从数据库中读取他们自己的“组”。
我使用的是javascript,检索“groups”的代码如下:
console.log("uid: ", uid)
db.collection("users/" + uid + "/groups")
.onSnapshot(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.data())
})
})
现在因为云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;
}
}
}
并试图访问用户/ 5lS2NA21UgbabEw4AkyWyef9FH42 /组,“userId”变量不评估为5lS2NA21UgbabEw4AkyWyef9FH42(我不知道它会是什么,但我猜“5lS2NA21UgbabEw4AkyWyef9FH42 / 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;
}
}
}
}