Jay
Jay

Reputation: 5074

Firebase Rules: Allow user to read data only if user is included in a child node

I am attempting to rewrite my database rules to only allow members of a specific 'collection' to access that collection only if that member is included in the teams list. Referring to the image attached below, this is what my rule currently looks like:

    {
        "rules": {
            "collection": {
                "$collection_id": {
                    "$teams" : {
                        ".read": "data.child('id').val() === auth.uid"
                    }
                }
            }
        }
    }

enter image description here

However this doesn't seem to work and I believe it's incomplete. How can I update my rules to match this design structure? If any change in my structure is necessary to support this, do pitch that and I will attempt to update the current production data.

Upvotes: 1

Views: 762

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

You could reach into the teams node like this:

{
    "rules": {
        "collection": {
            "$collection_id": {
                ".read": "data.child('teams').child(auth.uid).child('id').val() === auth.uid"
            }
        }
    }
}

Right now you have unnecessary redundancy in the teams node. The id of the child node is repeated in its own child id. You can simplify your database and rules if you simply set teams/{teamId} = true in the database, your rule could look like this instead to allow only users listed under teams to read the entire collection:

{
    "rules": {
        "collection": {
            "$collection_id": {
                ".read": "data.child(auth.uid).val() === true"
            }
        }
    }
}

Upvotes: 1

Related Questions