0

Let's say I have a Firebase Realtime database with the below data structure. And let's say I want to allow write access for uuid and content but not for locked. Is that possible to do with the Security Rules?

{
  "messages": { 
     "message1": {
        "uuid": "1234",
        "content": "Lorem ipsum",
        "locked": true
     }
  }
}

In Firestore you can do something like:

request.resource.data.keys().hasOnly(
  ['uuid', 'content']
)

Can the same be achieved for the Realtime Database?

Nick
  • 3,496
  • 7
  • 42
  • 96

1 Answers1

1

The trick to only allow specific children, is to allow those children and reject all others. For your example, that'd be:

{
  "rules": {
    ".read": true,
    ".write": true,
    "messages": {
      "$messageid": {
        "uuid": {
          ".validate": true
        },
        "content": {
          ".validate": true
        },
        "locked": {
          ".validate": true
        },
        "$other": {
          ".validate": false
        },
      }
   }
  }
}

This allows writing the named uuid, content and locked properties, and rejects any other properties with a wildcard capture rule.


If you want to not allow changing the value of uuid, you can do that with:

"uuid": {
  ".validate": "newData.val() == data.val()
},

See the documentation on new vs existing dat


Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks @Frank. However, what I meant was: let's suppose you don't want to allow writing to the `locked` property and only allow reading that property. So, allow reading for all three properties, but allow write only for `uuid` and `content`, but not `locked`. Then `validate` I think would need to be different for read and write. Is that possible? – Nick May 30 '23 at 13:11
  • That's not what the Firestore rules in your question do, but I added an example of how to prevent changing a specific property value. – Frank van Puffelen May 30 '23 at 13:17
  • Thanks Frank. I assume "If you want to now allow changing..." in your answer should be "If you want to NOT allow changing..."? – Nick May 30 '23 at 13:57