4

If I have a document saved at /recordTypeX/{autoKey}, with the following structure:

memberUserIds [object]
  hjfjkh32390u09j: true
  kjsklfjkslfklj3: true
  ....
  skfksdjk2249fks: true
someStringField: "Bork, bork, bork!"
someNumericField: 88

How do I write a security rule to check the existence of one of the memberUserIds? I've tried the following, but the CLI doesn't like the syntax.

allow read if resource.data.memberUserIds.$(request.auth.uid) == true;

I know that variables can be used in paths with get() and exists(), so I thought addressing a field using a variable would also be possible, but I can't get past the syntax error. Is this possible?

For some background, I'm trying to maintain a (small) list of userIds on each document in the collection such that I can do queries that allow me to retrieve all the documents in the collection which the current user is a member of.

I adopted this approach after reviewing a guide called working with lists, sets, and arrays that used to be available in the Firebase documentation, but seems to have been removed.

Thanks for any thoughts.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
HondaGuy
  • 1,251
  • 12
  • 29

1 Answers1

8

Here is an example of one of my fire base rules.

function containsResourceOwnerId() {
    // /database/{database}/documents/example/{exampleId}
    // exampleDocument => { abc123: true }, request.auth.uid = abc123
    return resource.data[request.auth.uid] == true;
}

You should be able to use the following

function isMemberOf() {
    return resource.data.memberUserIds[request.auth.uid] == true;
}

And use where ever you need the rule.

match /teams/{teamsId} {
    allow read: if isMemberOf();
Philip
  • 841
  • 6
  • 13
  • Thank you, @Philip. That's exactly what I needed. Your solution works, though I see now that the utility of this approach will be limited if a composite index will ever be required. I'll likely adjust my model. If anyone else ends up here with a similar question, be sure to also check out: https://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value – HondaGuy Aug 31 '18 at 04:08