skip to Main Content

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:

Here is authentication users to firebase

Realtime Database

Categories
This is categories table

Users
This is users table

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,
      });

Error
enter image description here
enter image description here
enter image description here

Is there anything wrong with the rules that am applying?

2

Answers


  1. When you’re using the following security rules:

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

    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:

    "categories": {
      ".write": "auth != null",
      ".read": "auth != null"
    }
    

    And this is because those category objects exist directly under the categories node and not under categories/$uid.

    Login or Signup to reply.
  2. 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 enter uid under Firebase UID field. You may have look at below screenshot.

    enter image description here

    You can refer this tutorial for more information.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search