0
votes

I am pretty confused about the Firebase security rules - about WORK FROM THE TOP-DOWN as the docs.

So I have this rule:

  "rules": {
    "taskUsers": {
      ".read": "auth != null",
      "$uid": {
       ".read": "auth != null",
       ".write": "auth != null && auth.uid == $uid",
      },
    },
  }

So all the user data can only be updated by the user who created them b/c of auth.uid == $uid. But under the firebasepath/taskUsers/$uid, I have a value called notification that I want other users can able to write. Like in a chat notification system - when other users contact this user, the "other users" can change / write the value notification (like +1). But with the above rule, "other users" when they post the contact, it will return permission denied. So if I do the rule like

"rules": {
    "taskUsers": {
      ".read": "auth != null",
      "$uid": {
       ".read": "auth != null",
       ".write": "auth != null && auth.uid == $uid",
       "notification": {
        ".write": "auth != null",
        },
      },
    },
}

The rule got ignored...So how can I create a rule just allow notification value under the taskUsers/$uid to be written by everyone who login?

1

1 Answers

1
votes

I have not tested it but this should point you in the right direction at the very least. Their rules get kind of tricky... I still maintain that one should have a WebService in front of Firebase for any data manipulation. How else does one implement non-trivial business logic?

"rules": {
    "taskUsers": {
      ".read": "auth != null",
      "$uid": {
       // authenticated users can write as long as they have a notification property
       ".write": "auth != null && (auth.uid == $uid || newData.hasChild('notification'))",
       "notification": {
       // Bonus rule: only increment the number by 1 or -1
           ".validate": "newData.isNumber() && ((!data.exists() && newData.val() === 1 || newData.val() === -1) || newData.val() === data.val()+1 || newData.val() === data.val()-1)",
        }
      },
    },
}