Search code examples
firebase-realtime-databasefirebase-security

How can I write the rule for the Firebase data structure below?


I want to write a rule in Firebase to allow only the user to be able to write to the database when the disable is set to false.

The structure of my database is as follows:

{
  "Users": {
    "UID": {
      "details": {
        "random key generated by push": {
          "disable": true,
        },
      }

Solution

  • To read a value from another node inside your security rules, you have to know the exact path to that node. So unless you know the value of "random key generated by push", there is no way to read that from the rules on one of the nodes above it.


    This usually means that you should change your data structure to have the disable flag at a known location under the UID node. For example:

    {
      "Users": {
        "UID": {
          "disable": true,
          "details": {
            "random key generated by push": {
            },
          }
    

    Now you can allow access to UID node like this:

    {
      "rules": {
        "Users": {
          "$uid": {
            ".read": "data.child('disable').val() === true"
          }
        }
      }
    }