Home > database >  Firebase Realtime Database user data access based on uid
Firebase Realtime Database user data access based on uid

Time:11-05

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

Error enter image description here

Is there anything wrong with the rules that am applying?

CodePudding user response:

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 && $uid === auth.uid",
  ".read": "auth != null && $uid === auth.uid"
}

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

CodePudding user response:

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.

  • Related