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

白昼怎懂夜的黑 提交于 2021-01-29 05:40:38

问题


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.

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.


回答1:


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. 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.



来源:https://stackoverflow.com/questions/57684247/firestore-security-rules-how-to-check-if-document-was-created-by-user-is-owner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!