1
votes

I am trying to use firebase database rules to prevent negative values.

{
"rules": {
    "products": {
        ".read": true,
        ".write": "auth != null",
        ".indexOn": ["subgroup", "group", "visibility"],
        ".validate": "newData.child('quantity').val() >= 0"
    }
}

However, using the the simulator to test the rule, I am always seeing write denied on validate rule:

".validate": "newData.child('quantity').val() >= 0"

I am using:

location: /products/-KQ1qLkeI3gefuGSFIL_

and

{
   "quantity": 0
}

I am using an authenticated user.

Any idea whats going on here ?

Thanks.

==== update:

changing rules to the following didn't help:

"products": {
        "$product": {
        ".read": true,
        ".write": "auth != null",
        ".validate": "newData.child('quantity').val() >= 0",
        ".indexOn": ["subgroup", "group", "visibility"]
      }
    }, 

Also, DB design:

DBRoot
    products
        -KQ1nPkLeqiTMzEzhrfW
            description:"Limited Edition"
            quantity: 5
            ...
1
Can you try writing directly to products instead of /products/-KQ1qLkeI3gefuGSFIL_? - André Kool

1 Answers

1
votes

Your validation rules are on /products, but you are writing to /products/[autoid]. Try modifying your rules like so:

{
  "rules": {
    "products": {
       "$pid": {
         ".read": true,
         ".write": "auth != null",
         ".indexOn": ["subgroup", "group", "visibility"],
         ".validate": "newData.child('quantity').val() >= 0"
       }
    }
  }
}

Simulated Rules