FireStore Rules : Read/Write user own document

Viewed 168

In Firestore I have 2 collections

A users collection and a periods collection. I need a rule for my period collection : Read and write only by the user who create the period.

users collection look like enter image description here

periods collection look like enter image description here

This is what I try with no success

service cloud.firestore {
  match /databases/{database}/documents {
    function userDoc() {
      return /databases/$(database)/documents/users/$(request.auth.uid);
    }

    match /users/{userId} {
      allow read: if true;
      allow create, update: if request.auth.uid == userId;
    }

    match /periods/{id} {
        allow read : if userDoc() == request.resource.data.user;
        allow write : if userDoc() == request.resource.data.user;
    }
  }
}
2 Answers

Replace

if userDoc() == request.resource.data.user

with

if userDoc() == request.resource.data.user_id

Other than that your security rule looks correct to me.

  • The object ‘request.resource.data.user’ doesn’t exist in your periods collection so it should be changed to ‘request.resource.data.user_id’.
  • Also the read and delete request doesn’t have a ‘request.resource’ object. So for the read and delete request, ‘request.resource.data.user_id’ should be replaced with ‘resource.data.user_id’.
  • I would suggest you to use more granular rules for write requests i.e. create, update, delete. For more details on firestore rules you can refer to this link.

For your use case please see the below firestore rule sample.

service cloud.firestore {
  match /databases/{database}/documents {
    function userDoc() {
      return /databases/$(database)/documents/users/$(request.auth.uid);
    }

    match /users/{userId} {
      allow read: if true;
      allow create, update: if request.auth.uid == userId;
    }

    match /periods/{id} {
        allow read, delete : if userDoc() == resource.data.user_id;
        allow update : if userDoc() == request.resource.data.user_id;
        allow create : if userDoc() == /databases/$(database)/documents/$(request.resource.data.user_id.path);
    }
  }
}
Related