'Firebase Realtime Database Allow read/write if string matches an attribute
My firebase realtime database structure:
stores
-store1234
-data
-specialKeyForStore1234
-store4567
-data
-specialKeyForStore4567
-...
My goal:
-data should be public readable for everyone, but only the store that owns the data should be able to add/edit/remove the data
Now in my webapp there is no sign-in authentication required to access the database, but to restricts others to change other stores data, I would like to implement something like this:
If store1234 wants to write/edit its own data, it needs to provide this specialKeyForStore1234.
The actual webapp of store1234 has this special key and can compare the value with the one from database to match, if there is a match, then let access for read and write. Otherwise refuse it.
How can it be done?
Solution 1:[1]
To send the special key, add a field specialKey
to the model.
Basically, check that the model-key specialKey
is equal to the database-field specialKey
.
The obvious problem with this approach is, that the specialKey
of the model is then persisted with every object, there is a suggestion for that below, too.
Note: newData
is the incoming model-data.
The code below might point in the right direction. I did not test it and might have made wrong assumptions.
Rule
{
"rules": {
"shops": {
"$shop_id" {
"payload" {
".read": if true,
// OPTION A
".write": "root.child(shops).child($shop_id)
.child(newData.child('specialKey)).exists()"
// OPTION B
//
// Try deleting the secrectKet in the model.
// No idea if this works in real life.
// === seems to be correct for assigning values?
".write": "root.child(shops).child($shop_id)
.child(newData.child('specialKey)).exists()
&& newData.child('specialKey).val() === '' "
},
"specialKey" {
// is READ:false ok to be processed by rule above?
".read": if false,
".write": if false,
}
}
}
}
}
Data Structure
{
"shops": {
"shop-a": {
"payload": "yourPayload",
"SuperSecretSpecialKey123": true
}
}
}
Source
https://firebase.google.com/docs/rules/rules-language#building_conditions
Bottom Line
It might be worth considering a normal authentication process, then one could assign users write-roles and user proper authentication.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dabbel |