ditoslav
ditoslav

Reputation: 4872

Why cloud firestore rule wont match my path pattern?

So I have a simple database and I want to make a simple rule but for some reason it doesn't want to match my collection

enter image description here

service cloud.firestore {
  match /databases/{database}/documents {

    match /userPrivate/{user=**} {
      allow read, write: if request.auth.uid == user;
    }

  }
}

enter image description here

enter image description here

Upvotes: 3

Views: 830

Answers (2)

Renaud Tarnec
Renaud Tarnec

Reputation: 83068

You need to adapt your rules as follows:

service cloud.firestore {
  match /databases/{database}/documents {

    match /userPrivate/{user} {
      allow read, write: if request.auth.uid == user;
    }

  }
}

Your wildcard must point to a single path document (which is what you get by doing {user}) and not match any document under the userPrivate collection (which is what you get by doing {user=**}, in other words "the rest of the path").

In case you want to allow the user to read/write all the documents included in the user document's sub-collections with the same security level, the following rule will do the trick:

service cloud.firestore {
  match /databases/{database}/documents {

    match /userPrivate/{user} {
      allow read, write: if request.auth.uid == user;

      match /{userCollec=**} {
        allow read, write: if request.auth.uid == user;
      }

    }

  }
}

I would suggest you watch this official Firebase video on Firestore security rules: https://www.youtube.com/watch?v=eW5MdE3ZcAw&, in particular the part starting at 5 minutes.

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317402

You're not specifying the document to fetch correctly. In the text box that asks you for the location of the document, don't add /databases/(default)/documents. That is added for you automatically. You should specify the path to the document using the collection and document id. For example: /userPrivate/uid where "uid" is the document id. You should probably also turn on authentication in the simulator so that the id is matched.

Also bear in mind that when you use a wildcard match with two stars like /userPrivate/{user=**}, then user variable will contain the entire path of the document, including any subcollections. This means that you rule will not work for documents within subcollections.

Upvotes: 1

Related Questions