Tsabary
Tsabary

Reputation: 3938

Why do my Firestore rules prevent me from getting my documents?

I am setting my firebase rules, and I have one query that keeps throwing back at me Uncaught (in promise) FirebaseError: Missing or insufficient permissions.

I've looked at my rules and tried to figure out what I might be doing wrong, but can't find what it is.

This is my query:

  const data = await db
    .collection("templates")
    .where("user_ID", "==", userID)
    .get()

And these are my relevant rules:

match /templates/{template}{
  allow read, write, delete: if request.auth.uid == request.resource.data.user_ID;
}

I only have this one rule for the templates collection, so there's no overwriting issues happening.

Each document in this collection has a field user_ID which is the uid of the user who posted it.

I currently have just one document there for testing.

What am I doing wrong to get that error?

If I change it to just be if true then I stop getting this error - so I know that this rule is the one causing the issues.

Upvotes: 0

Views: 27

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83068

As explained in the doc:

The resource variable refers to the requested document, and resource.data is a map of all of the fields and values stored in the document.

When writing data, you may want to compare incoming data to existing data. In this case, if your ruleset allows the pending write, the request.resource variable contains the future state of the document.

So your rule is not correct when you want to read, it should be:

match /templates/{template}{
  allow read: if request.auth.uid == resource.data.user_ID;
  allow write: ....
}

FYI, it's really worth watching the official video.

Upvotes: 1

Related Questions