Thijs Koerselman
Thijs Koerselman

Reputation: 23270

How to target nested fields in a Firestore security rule

My app has the unfortunate design that user settings are nested under "settings" in the user object. I now find myself in a situation where I want to allow the app to only update a specific field in the settings. So I've attempted to write a rule like this:

match /users/{userId} {
      allow get: if userMatchesId(userId)
      allow update:
        if userMatchesId(userId)
        && request.resource.data.keys().hasOnly(['settings.someSetting'])
        && request.resource.data.settings.someSetting is list;
}

This syntax for field paths does not seem to be supported, and the documentation has no mention of this either. Is there a way?

If not, I will reconsider moving settings to its own collection, but it involves some refactoring of course...

Upvotes: 1

Views: 295

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50840

The keys() method returns direct keys only and not the nested ones. If you want to get affected keys within settings map then try the following:

match /users/{userId} {
      allow get: if userMatchesId(userId)
      allow update:
        if userMatchesId(userId)
        && request.resource.data.settings.keys().hasOnly(['someSetting'])
        && request.resource.data.settings.someSetting is list;
}

Upvotes: 1

Related Questions