collectionGroup查询的Firebase firestore安全规则



我正在尝试从客户端查询和过滤collectionGroup:

const document = doc(db, 'forums/foo');
const posts = await getDocs(
query(
collectionGroup(db, 'posts'),
orderBy(documentId()),
startAt(document.path),
endAt(document.path + 'uf8ff')
)
);

我的自定义用户声明如下所示:

{ forumIds: ['foo'] }

文档告诉我要添加以下安全规则:

match /{path=**}/posts/{post} {
allow read: if request.auth != null;
}

但是这是一个安全漏洞,因为它意味着任何人都可以读取所有的posts集合。我只希望用户在论坛上阅读帖子。没有更好的方法来保护collectionGroup查询吗?

(1) I have try:

match /{path=**}/posts/{post} {
allow read: if path[1] in request.auth.token.forumIds;
}

但是我得到这个错误:Variable is not bound in path template. for 'list' @ L49.

(2)我也试过:

match /{path=**}/posts/{post} {
allow read: if resource.__name__[4] in request.auth.token.forumIds;
}

但我得到这个错误:Property __name__ is undefined on object. for 'list' @ L49.

我也试着用debug调试前面的两个安全规则,它们都返回true

根据您声明的需求,您根本不需要集合组查询。集合组查询打算获取所有命名集合中的所有文档。您只能像处理其他查询一样,根据文档的内容筛选结果。

既然你有一个论坛列表,用户应该能够阅读,你应该只查询他们每个单独,并结合在应用程序的结果。安全规则将无法过滤掉他们,因为安全规则不是过滤器。

参见:

  • https://medium.com/firebase developers/what - -这意味着,firestore -安全-规则- - - - - - -不-过滤- 68 ec14f3d003
  • https://firebase.google.com/docs/firestore/security/rules-query rules_are_not_filters

最新更新