gpt4 book ai didi

javascript - 火存储 : Access documents in collection user has permission to

转载 作者:行者123 更新时间:2023-12-01 00:58:51 25 4
gpt4 key购买 nike

我有一个名为公告的集合,用于存储数据。但是,每个文档都有一个名为“权限”的字段,其中包含权限级别字符串。我编写了函数来根据用户的权限级别和资源的权限来确定用户是否具有访问权限。

当我为应该有效的单个文档设置 onSnapshot 回调时,我得到了响应。一旦我将其切换到获取集合的快照,它就会出现无效权限错误。根据我的发现,如果用户有可能无权访问集合中的任何文档,firestore 就会失败。我应该使用什么模型?如何获取用户也应该有权访问的文档?

规则

match /chapters/{chapter} {
function isMember() {
return exists(/databases/$(database)/documents/chapters/$(chapter)/members/$(request.auth.uid))
}

function getUser() {
return get(/databases/$(database)/documents/chapters/$(chapter)/members/$(request.auth.uid))
}

function hasPermission(userPermission, documentPermission) {
return documentPermission == "all" || userPermission == "admin" || userPermission == documentPermission
}

allow read: if isMember()

match /announcements/{announcement} {
allow read: if isMember() && hasPermission(getUser().data.permissions, resource.data.permissions)
}
}

作品vvv

firestore.collection("chapters").doc("chapter-1").collection("announcements").doc("doc1").onSnapshot(doc => {
const announcements = doc.data()

console.log(announcements)
})

不行vvv

 firestore.collection("chapters").doc("chapter-1").collection("announcements").onSnapshot(docs => {
docs.forEach(doc => {
const announcements = doc.data()

console.log(announcements)
})
})

最佳答案

这是因为,在查询的情况下,规则不是过滤器

doc 中所述,

When writing queries to retrieve documents, keep in mind that security rules are not filters—queries are all or nothing.

您需要“编写查询以适应安全规则的限制”

另一方面,

this behavior applies to queries that retrieve one or more documents from a collection and not to individual document retrievals. When you use a document ID to retrieve a single document, Cloud Firestore reads the document and evaluates the request using your security rules and the actual document properties.

这就是为什么当您仅使用

查询一个文档时它会起作用

firestore.collection("chapters").doc("chapter-1").collection("announcements").doc("doc1").onSnapshot()

<小时/>

因此,为了查询集合,您需要向查询添加过滤器,如下所示:

firestore.collection("chapters").doc("chapter-1").collection("announcements").where("permissions", "==", "xxxxx");

关于javascript - 火存储 : Access documents in collection user has permission to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56296046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com