npk
npk

Reputation: 1810

Firebase Database Rules: different rule for parent and child

I have my database like this:

Firebase Rules ScreenShot

user123 is an admin. Hence he should be able to loop through all nodes in entries. Others cannot see child of entries unless uid of entryID is auth.uid

How shall I set rules for this? If there is no possible way, any suggestion to change dataBase :)

Upvotes: 0

Views: 1623

Answers (1)

nagabandaru
nagabandaru

Reputation: 645

if you already know admin is, in your question user123. Then you database rule should be like

"entities": { 
  "$entryId":{
      // you don't what others to see other to see teh data
    ".read": "auth.uid == 'user123'"
      // any one who is logged in should write to the /entries node
    ".write": "auth.uid != null"
  }
}

In case you what to make the rule more dynamic then you can do

"entities": {
  "$entityId":{
      // you don't what others to see other to see teh data
      ".read": "root.child('users').child(auth.uid).child('isAdmin').val() == true || root.child('entities').child($entityId).child('uid').val() == auth.uid"
      // any one who is logged in should write to the /entries node
      ".write": "auth.uid != null"
  }
}

You can get more info from here https://firebase.google.com/docs/reference/security/database/

Alternatively, You can change your entries model to user specific

{
  "entities" :{
     "user465": {
       "entry456": {
         "text" : "Some sample text"
       }
     }
   }
}

In this case, you write you rule

"entities": {
  "$userId":{
     // you don't what others to see other to see teh data
     ".read": "root.child('users').child(auth.uid).child('isAdmin').val() == true || $userId == auth.uid"
     // any one who is logged in should write to the /entries node
     ".write": "auth.uid == $userId"
  }
}

Upvotes: 2

Related Questions