0
votes

I have set up rules for my Cloud Firestore database, and I can't figure out how to get the userId wildcard on the following call.

The first snippet works, because I am searching on the users node, and the document Id (resource.id) is the same as the uid.

The second snippet does not work when writing to, for example, users/uid/items/itemId. Resource.id in this case would be equal to itemId, and trying to map the wildcard as you see below, doesn't work. I've also tried request.path[6] and request.path[1] as per the Firebase Rules documentation but to with success.

    match /users/{user} {
      allow read;
      allow write: if request.auth.uid == resource.id; //WORKS LIKE A CHARM
    }

    match /users/{userId}/{document=**} {
      allow read;
      allow write: if request.auth.uid == request.path['userId']; //ALWAYS FAILS
    }

EDIT 1: For example, when I make a POST to /users/12dij1od/items/itemId with the parameters of the new item, I would expect it to go through for user 12dij1od, but not any other. As of now, it fails for everybody.

I have also tried "allow write: if request.auth.uid == userId"

Any ideas of what I might be doing wrong?

EDIT 2:

If there is a way to solve it declaring all nested collections, I am open to doing it as so as well. Something like:

        match /users/{userId} {
          allow read;
          allow write: if request.auth.uid == request.path['userId']; //ALWAYS FAILS

          //Nested Subcollection
          match /items/{item} {
          allow read;
          allow write: if request.auth.uid == [ACCESS TO USERID HERE];

        }
1
Have you tried just saying request.auth.uid == userId?Doug Stevenson
Can you update your question to include the code that you expect to give a result with that second set of security rules?Frank van Puffelen
Doug yes I have. Always fails as well. Frank not sure if I answer your question with my edit. Again, with any comparison, it fails for all users..Jacobo Koenig

1 Answers

0
votes

For anybody else with the same question, by trial an error I got to the following code that does work:

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

        function getUserId() {
          return get(/databases/$(database)/documents/users/$(userId)).id
        }

        match /{document=**} {
          allow read;
          allow write: if getUserId() == request.auth.uid;
        }

    }