简体   繁体   English

Firestore安全性规则如何检查文档是否由用户(所有者)创建

[英]Firestore security rules how to check if document was created by user (is owner)

I have a firestore database with two collections: 'notes', where each document stores the content for each note and the authorId (which corresponds to the currently signed in users uid), and 'users', where the name of the user is stored and the id of each document is the uid of the user. 我有一个具有两个集合的firestore数据库:“笔记”(每个文档存储每个笔记的内容和authorId(对应于当前登录的用户uid))和“用户”(用于存储用户名)每个文档的ID是用户的uid。 This way, the author of the note is connected to the user in firestore. 这样,便笺的作者就可以在Firestore中连接到用户。 I am trying to make a web application where only the notes that the user created (authorId == uid) are shown and the other notes are not. 我正在尝试制作一个Web应用程序,其中仅显示用户创建的注释(authorId == uid),而其他注释则不显示。

I've tried comparing resource.data.authorId and request.resource.data.authorId with request.auth.uid. 我试过比较resource.data.authorId和request.resource.data.authorId与request.auth.uid。

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /notes/{note}{
        allow read: if request.auth.uid == resource.data.authorId;
    }
  }
}

I wanted only the notes that the user created to show, but no notes show at all with this rule. 我只希望用户创建的注释显示出来,而此规则根本不显示注释。

My quick guess is that your code is trying to read all documents from the collection, and that you expect the security rules to filter the data. 我的快速猜测是,您的代码正在尝试从集合中读取所有文档,并且您希望安全规则可以过滤数据。 That is not how Firebase security rules work. 这不是Firebase安全规则的工作方式。 They don't filter the data by themselves, but instead merely check to ensure that any read operation is allowed. 它们不会自行过滤数据,而只是检查以确保允许任何读取操作。

This means to to allow secure access to only the documents that the user created themselves, you'll need: 这意味着仅允许安全访问用户自己创建的文档,您将需要:

  1. To write code that queries to only request the documents that the user created themselves. 编写查询仅请求用户创建自己的文档的代码。
  2. To write security rules that then validate that only this type of query is allowed. 编写安全规则,然后验证仅允许这种类型的查询。

Your security rules seem do the second bit, so all you need to do is also write that query into your application code. 您的安全规则似乎是第二位的,因此您所要做的就是将查询查询写入您的应用程序代码中。

For more on this see the documentation on securely querying data . 有关更多信息,请参阅有关安全查询数据文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM