Search code examples
firebasefirebase-realtime-databasefirebase-security

Firebase Realtime Database user data access based on uid


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?


Solution

  • 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.