简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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