Home > other >  How to target nested fields in a Firestore security rule
How to target nested fields in a Firestore security rule

Time:10-20

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...

CodePudding user response:

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;
}

CodePudding user response:

As of now the keys() method returns only direct keys. I have had similar issue with overly complicated rules. I would highly recommend using Cloud Functions for Firebase to check these pre-conditions, however if you do want to keep using rules to check them, the move to separate collection is always an option.

  • Related