Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore Security Rules - How Do I Use a Variable for a Field Name?

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.

like image 426
HondaGuy Avatar asked Jan 27 '23 12:01

HondaGuy


1 Answers

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();
like image 165
Philip Avatar answered Feb 13 '23 06:02

Philip