mik
mik

Reputation: 809

Firestore rule on uid doesn't work for unknown reason

I have an 'owner' field in my documents to entitle only the owner to read the document, and only a new document that its 'owner' field is the uid of the user, can be written:

allow read: if request.auth.uid == resource.data.owner; allow create, write : if request.auth.uid == request.resource.data.owner;

The creation and update rule works as expected! I tested and saw that if the 'owner' field of the record in the new data is not the user's UID then it doesn't work!

The problem is the 'read' section. I wasn't able to read records. Only when I changed to allow read: request.auth.uid != null, I was able to read. I triple checked that the records has an 'owner' field that is exactly the same as the UID, also in debug.

I'm have experience with Firebase, and I have no idea what is the problem here.

Upvotes: 0

Views: 66

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83103

Since you indicate that "[You weren't] able to read records" (with an S at records), your problem most probably comes from the fact that security rules are not filters, as explained in the documentation:

Once you secure your data and begin to write queries, keep in mind that security rules are not filters. You cannot write a query for all the documents in a collection and expect Cloud Firestore to return only the documents that the current client has permission to access.

You don't show the query used to read the Firestore documents, but let's imagine your documents are in a collection named collection.

With a query like

query = db.collection("collection")
query.get().then(....);

you are querying independently of the User ID, hence the problem.

You need to adapt your query with the where() method, as follows:

//get the value of uid
query = db.collection("cities").where("owner", "==", uid)
query.get().then(....)

Upvotes: 1

Related Questions