Fengson
Fengson

Reputation: 4912

Firestore rules based on path component and other collection

I am trying to establish a rules, where user would only be able to perform operations on Chat messages after they have made a purchase of one of the services.

My database structure looks like this:

I have purchases collection: purchases/{purchaseId} which contains buyer_id field. I also have messages collection: /channels/{purchaseId}/thread/{threadId}.

I want to allow CRUD operations if the users in thread are the same as buyer_id from purchases collection, in purchaseId document.

This is what I've tried, using current user's ID (auth) for now. This doesn't work, either. Ideally, I would substitute request.auth.uid with the field from the document I am trying to access, but this would do for now.

match /channels/{purchaseId}/thread/{threadId} {
    allow read, create, update, delete: if get(/databases/{database}/documents/purchases/{purchaseId}).data.buyer_id == request.auth.uid;
}

I am getting the standard permissions error. What am I missing?

Upvotes: 0

Views: 44

Answers (1)

l1b3rty
l1b3rty

Reputation: 3660

You syntax is wrong when defining the path. Try this:

match /channels/{purchaseId}/thread/{threadId} {
    allow read, write: if get(/databases/$(database)/documents/purchases/$(purchaseId)).data.buyer_id == request.auth.uid;
}

Substituting request.auth.uid with the field from the document:

match /channels/{purchaseId}/thread/{threadId} {
    allow read, write: if get(/databases/$(database)/documents/purchases/$(purchaseId)).data.buyer_id == resource.data.buyer_id;
}

Upvotes: 1

Related Questions