I’m trying to create a rule for create/access the FRD data based on authenticated user. But am getting an error where running the Rules Playground
What I want is, Users are creating the categories. So Users is able to only read their categories and update those categories.
Rule:
{
"rules": {
"users": {
"$uid": {
".write": "auth != null && $uid === auth.uid",
".read": "auth != null && $uid === auth.uid"
}
},
"categories": {
"$uid": {
".write": "auth != null && $uid === auth.uid",
".read": "auth != null && $uid === auth.uid"
}
}
}
}
Auth Users:
Realtime Database
Categories Write function in Flutter
String uId = await userId();
final databaseRef = FirebaseDatabase.instance.ref('categories');
var data = await databaseRef.get();
var index = data.children.length;
await databaseRef.child('$index').set(<String, dynamic>{
"name": categoryBody.name,
"description": categoryBody.description,
"uid": uId,
"id": index,
});
Is there anything wrong with the rules that am applying?
2
Answers
When you’re using the following security rules:
It means that you allow the user to write/read to/from every child that exists under your
categories/$uid
node. So when you try to apply those rules to your actual database structure, it’s the expected behavior to see that Firebase servers reject the operations since it doesn’t find any$uid
level in your database schema. To solve this, you have to remove that extra$uid
level from rules like this:And this is because those category objects exist directly under the
categories
node and not undercategories/$uid
.I tried to replicate your issue, but I can able to successfully test rules without errors.
The rules you are using are for authenticated users but you are testing for unauthenticated users. Means you have not enabled
Authenticated
field.And you have to enter
/categories/uid
instead of/categories
under the location and you should enteruid
underFirebase UID
field. You may have look at below screenshot.You can refer this tutorial for more information.