VIKAS KOHLI
VIKAS KOHLI

Reputation: 8430

How to prevent read access for only node or some keys in realtime database firebase?

I want to prevent read access for only one node.

let's assume I have nodes like that

"0" : {
//somedata
},
"1": {
//somedata
},
"2": {
//somedata
},
"3": {
 //my private data
}

Now I won't want "3" to be read from any connections. What rules should be written there to prevent its read and write access?

I tried using rules like:-

{
  "rules": {
      "$3": {
        ".read": false,
      }
    ".read": true,
    ".write": "auth!=null && auth.uid == 'myuid'",
  }
}

If I do this then in the child_added it gives me all nodes also changing "$3" to "3" doesn't matter right now

  {
     "rules": {
       ".read": true,
       ".write": "auth!=null && auth.uid == 'myuid'",
       "$3": {
           ".read": false,
        }
     }
  }

the second one gives all nodes because in the very first line of the rule I used the read key as true i.e working on the cascading rule as .read and .write rules work from top-down from firebase docs Firebase Rules Docs

If any suggestions for the same or different approach I need to do this, please suggest me that? Thanks, folks!

Upvotes: 0

Views: 598

Answers (2)

samthecodingman
samthecodingman

Reputation: 26171

You were close. As you read correctly, the rules cascade from higher tiers down to the more specific ones. So if you approve the write at a higher tier (as you did for the root of your database) that "allowed" write permission applies to your entire database.

The $ is used to identify a variable name in the path. So when you use "$3" you are actually defining a variable named "$3", not referencing the specific key "3". What you are looking to do is specify a variable that is used for all values that aren't "3", which by convention, is called "$other".

{
  "rules": {
    "3": {
      ".read": false,
      ".write": false
    },
    "$other": { // any key not named above at this level  
      ".read": true,
      ".write": "auth!=null && auth.uid == 'myuid'"
    }
  }
}

Upvotes: 1

touhid udoy
touhid udoy

Reputation: 4442

This should work:

{
  "rules": {
      "3": {
        ".read": false,
        ".write": false,
      }
    ".read": true,
    ".write": "auth!=null && auth.uid == 'myuid'",
  }
}

1st you are checking, if the data is "3", block it and return. If not check below rules (in this case, allow authenticated users).

Upvotes: 0

Related Questions