英文:
Problem in rules of Firestore (collection group)
问题
我想从Firestore获取数据。我在Firestore的书籍结构中有以下内容:
Books --Book1.....name
.....author
.....user_id
.....describe
--Book2.....name
.....author
.....user_id
.....describe
并使用以下代码来获取它:
FirebaseFirestore.instance
.collectionGroup("Books")
.get()
.then(
(res) => print("成功完成"),
onError: (e) => print("完成时出错:$e"),
);
我在Firestore的规则中为组集合设置了以下规则:
match /{path=**}/Books/{book} {
allow read: if request.auth != null && request.auth.uid == resource.data.user_id;
}
我为此应用设置了Firebase身份验证。在编译应用程序并登录后,当我尝试获取书籍时,我看到以下错误:
调用者没有执行指定操作的权限。
英文:
I want to get data from Firestore.
I have these structures for books in FireStore
Books --Book1.....name
.....auteur
.....user_id
.....describe
--Book2.....name
.....auteur
.....user_id
.....describe
and use this code to get it
FirebaseFirestore.instance
    .collectionGroup("Books")
    .get()
    .then(
      (res) => print("Successfully completed"),
      onError: (e) => print("Error completing: $e"),
    );
I set these rules for group collection in the rules of Firestore.
match /{path=**}/Books/{book} {
allow read: if request.auth != null && request.auth.uid == resource.data.user_id;
}
And I set Firebase Authentication for this app
After compiling the app and logging in to the app
When I want to get the book I see this error
The caller does not have permission to execute the specified operation.
答案1
得分: 1
以下是翻译好的部分:
看起来你期望规则只过滤用户 UID 等于文档的 user_id
字段的文档。这不是规则的工作方式。文档明确指出规则不是过滤器。你的规则要求你的应用程序中的查询必须指定一个筛选器,将 user_id
字段的值设置为用户的 UID。
FirebaseFirestore.instance
.collectionGroup("Books")
.where("user_id", isEqualTo: uid)
其中 uid
是用户的 UID。
这使查询符合规则,因此它现在只请求规则已授予读取访问权限的文档。
英文:
It looks like you are expecting that the rule will filter only documents where the user's UID equals the document's user_id
field. That's not how rules work. The documentation is clear that rules are not filters. What your rule requires is that the query in your app must specify a filter on the user_id
field with the value of the user's UID.
FirebaseFirestore.instance
.collectionGroup("Books")
.where("user_id", isEqualTo: uid)
Where uid
is the user's UID.
This makes the query match the rule, so it is now only requesting documents that the rule has granted read access.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论