Indium Indeed
Indium Indeed

Reputation: 11

Firebase Realtime Database - Rules - Does two objects have at least one common child?

I am trying to check, if two objects have at least one common child. In the following example I want to be able to be control, if people can read org.money.value.

The right to read is determined by comparing the children of org.keys and users.{auth.uid}.keys. If there is a common key, reading would be allowed.

Database JSON:

{
    "org" : {
        "keys" : {
            "red" : {
                "value" : "..."
            },
            "blue" : {
                "value" : "..."
            }
        },
        "money" : {
            "value" : "..."
        }
    },
    "users" : {
        "John" : { // in reality John == auth.uid of a user
            "keys" : {
                 "red" : {
                     "value" : "..."
                 }
            }
        },
        "Alice" : { // in reality Alice == auth.uid of a user
            "keys" : {
                 "green" : {
                     "value" : "..."
                 }
            }
        }
    }
}

Rules:

"rules:"{
    "org" : {
        "money" : {
            // can read if "org.keys" and "users.auth.uid.keys" 
            // have at least one common child name.
            // With the above data reading would be allowed for John,
            // but not for Alice.
            ".read" : what to write here?
        }
    }
}

Is it possible to make this work?

By the way, the organization does not know the auth.uid of users.

Upvotes: 0

Views: 429

Answers (2)

Vladimir Gabrielyan
Vladimir Gabrielyan

Reputation: 801

another solution could be storing endpoint in the database like this

usersShareOrg
    { 
       "John": { "Org" : true }
       "Alice": {"Org": false}
    }

and these values would be calculated and stored every time you added new user or org.keys entity.

Upvotes: 0

Ian Richard
Ian Richard

Reputation: 525

I can't think of any way that you could do this determination in the JSON rules with your current database structure. I would suggest altering your structure to allow for this type of read determination. Here's a potential solution I came up with, which will require more filtering on client side:

When you create a new user key, loop through the org keys to see if it is already contained there. If so, add a BOOL to the user object, perhaps "canReadMoney" and set it to true. Then, your rule for money would look something like this:

"rules:"{
  "org" : {
    "money" : { 
        ".read" : "root.child('users').child(auth.uid).child('canReadMoney').val==true"
    }
  }
}

Upvotes: 0

Related Questions