Reputation: 11
This is my first question, so if I miss to include something please tell me, and many thanks for reading it.
I have a realtime database with this structure:
-transactions
-uid
-transaction1...
When adding a new transaction with these rules:
{
"rules": {
"transactions": {
"$uid":{
".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid",
}
}
}
}
And this url: (I am using the REST API)
POST https://{{appName}}.firebaseio.com/transactions/{{userId}}.json?auth={{TOKEN}}
With this data:
{
"title": "Postman Test",
"amount": 50,
"date": "2020-11-15",
"category": "other"
}
It works as expected. But when I add the following validation:
{
"rules": {
"transactions": {
"$uid":{
".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid",
".validate": "newData.hasChildren(['title','amount'])",
}
}
}
}
It return the following error: "error": "Permission denied"
If i put !newData.hasChildren(['title', 'amount'])
instead, it works, so i assume it is not reading the fields correctly.
I should mention that when i try this rule in the firebase page, they work, so i am confused.
I have read the documentation and searched for similar errors, but i can't fix it, so any help would be really appreciated.
Thank you very much.
Upvotes: 0
Views: 253
Reputation: 11
I finally could find a solution, so I would post it here in case anyone has the same problem.
When using POST
in Firebase Realtime Database
, it creates a new node with a new automatic index, so all i had to add was the "$id" (or any other name) field to account for that, as follows:
{
"rules": {
"transactions": {
"$uid":{
".read": "auth.uid == $uid",
".write": "auth != null && auth.uid == $uid",
"$id":{
".validate": "newData.hasChildren(['amount','category','type','date'])",
"amount": {
".validate": "newData.isNumber() && newData.val() >= 0",
},
"category": {
".validate": "newData.isString()",
},
"type": {
".validate": "newData.isString()",
},
"date": {
".validate": "newData.isString()",
}
}
}
}
}
}
Upvotes: 1