Search code examples
firebasevalidationfirebase-realtime-databasefirebase-security

How can I apply a validation security rule to the key in Firebase's Realtime Database


I'm having some confusion understanding validation security rules for Firebase's Realtime Database. The way I have my database set up currently looks like this:

(Database ID)
  users
    (Google UID)
      dayRatings
        2022-01-01: 2
        2022-01-02: 4
        2022-01-03: 5
      settings
        (Not implemented yet)
    (Google UID)
      dayRatings
        2022-01-01: 3
        2022-01-02: 1
        2022-01-03: 1
      settings
        (Not implemented yet)

The user can add their own rating, but the rating is not validated. I would like to validate both the key of the rating (e.g. 2022-01-01) and the value, but I'm confused on how I can perform validation on these, since the key can be different depending on the user's choice.

Right now, my security rules just ensure that users can only read and write to their own document, but the data is not validated in any way.

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

How can I perform validation if the key is not fixed? Am I even structuring my database correctly?

Any help would be very appreciated.


Solution

  • You can add another wildcard capture variable for the date:

    {
      "rules": {
        "users": {
          "$uid": {
            ".read": "auth != null && auth.uid == $uid",
            ".write": "auth != null && auth.uid == $uid"
            "$date": { // 👈 capture any child node
              ".validate": "..." // 👈 validate its value
            }
          }
        }
      }
    }
    

    The $date in here is the same as $uid, just with a different variable name and on a different level in the JSON.