Gaandmit Gaandmit - 1 month ago 18
Java Question

Firebase rules to allow some user access

enter image description here
I would like only user2, user3 to view user1's info from DB and not user 4.

I know I need to do something in the JSON rules:

THE UIDUser2, UIDUser3 Would be replaced with the actual ID's when User1 allowed permission via the app.

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


This is my edit so far:

{
"rules": {
"Users":{
"UIDHERE":{
".read": auth.uid ==??
}
}
}

}


How do I finish the rule? I want to retrieve the key's from the
Allowed
area to here?

Answer

So you want only users whose ids are in Allowed node read other users information. Right?

If so... Here is rules for it.

"Users": {
  "$uid": {
    ".read": "root.child('Users/Allowed/'+auth.uid).exists()"
  }
}

[UPDATED]

$uid is an example of $ variables (you can give it different name but it must start with $) which dynamically gets the value of key under Users location.

For example: The rule what I have given you only allows users under Allowed node to read other users info, But it will block user to read his own information if this user is not in Allowed node. If you want to add this too you need to change your rules like this.

"Users": {
  "$uid": {
    ".read": "$uid == auth.id || root.child('Users/Allowed/'+auth.uid).exists()"
  }
}

=========================================================================

In firebase rules there are predefined variables such as, now, root, auth, data, newData and $ variables.

When you have a $location in your rules structure, you can use a matching $ variable within your rule expression to get the name of the actual child being read or written. So suppose we want to give every user read and write access to their own /users/ location. We could use:

Copied from firebase docs https://firebase.google.com/docs/reference/security/database/#location

If you want to know more about firebase security rules read the following section.

https://firebase.google.com/docs/database/security/

P.S.

Your structure is not so good. Data under Users node is jumbled. You should not have Allowed node on the same level as userIds. Instead it would be better if you either create new node (allowedUsers) at Users node level and move Allowed data there.

AllowedUsers
  - userid2
  - userid3
Users
  - userid1
  - userid2
  - userid3
  - userid4
Comments