0
votes

I'm trying to secure my database and i want to secure the messages. My structure is messages/{chatid}/chat/messageArray (the chatid is like userid1-userid2). So i would like to check in security rules if chatid contain userid. I tried something it's working in simulator but i have a problem because in my code i query collection group and firestore deny acces. I make something like db.collection("messages").where("users", "array-contains", user.uid).onSnapshot..... If someone know how can i secure messages data i could be great.

match /messages/{chatId}/{document=**} {
  allow read, write: if chatId.matches('.*'+request.auth.uid+'.*');
}
1

1 Answers

1
votes

The rule you're showing here does not match your example query. The rule can only match documents in a subcollection of documents in the messages collection. Your query is trying to read documents immediately in the messages collection. The glob wildcard can not match zero path components. Only in rules version 2 can a glob wildcard match nothing.

Your options are to either set the rules_version = '2'; at the first line of your rules, or add another rule that matches documents in messages without using a glob wildcard:

match /messages/{chatId} {
  allow read, write: if chatId.matches('.*'+request.auth.uid+'.*');
}

I will encourage you instead not to try to match on the contents of chatId, and instead use fields of the documents. Your query should also use those fields to filter queries. This is more straightforward.