Firestore安全性规则如何检查用户是否创建了文档(是所有者) [英] Firestore security rules how to check if document was created by user (is owner)

查看:40
本文介绍了Firestore安全性规则如何检查用户是否创建了文档(是所有者)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个集合的firestore数据库:注释",其中每个文档存储每个注释的内容和authorId(对应于当前登录的用户uid),以及用户",其中的名称用户已存储,每个文档的ID是用户的uid.这样,便笺的作者就可以在Firestore中连接到用户.我正在尝试制作一个Web应用程序,其中仅显示用户创建的注释(authorId == uid),而其他注释则不显示.

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. This way, the author of the note is connected to the user in 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.

我尝试将resource.data.authorId和request.resource.data.authorId与request.auth.uid进行比较.

I've tried comparing resource.data.authorId and request.resource.data.authorId with 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.

推荐答案

我的快速猜测是您的代码正在尝试从集合中读取所有文档,并且您希望安全性规则可以过滤数据.这不是Firebase安全规则的工作方式.它们不会自行过滤数据,而只是检查以确保允许任何读取操作.

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. 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. 编写查询仅请求用户自己创建的文档的代码.
  2. 编写安全规则,然后验证仅允许这种类型的查询.

您的安全规则似乎是第二位的,因此您所要做的就是将该查询写到您的应用程序代码中.

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.

这篇关于Firestore安全性规则如何检查用户是否创建了文档(是所有者)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆