Search code examples
firebasefirebase-realtime-databasefirebase-authenticationfirebase-security

Managing team permissions and allowing two users from the same team to access a node


I allow login with Google to my Firebase web app. I control access to the database by the auth.uid:

 {
  "rules": {
     "users": {
        "$uid": {          
          ".read": "auth.uid === $uid",
          ".write":"auth.uid !== null",
             "images": {
                ".read": "auth.uid === $uid",
                ".write":"auth.uid === $uid",
      },
 ...

I want to enable other users in the user's team to access his/her images. I went through the docs but couldn't find a way to accomplish that. Any ideas?


Solution

  • Security rules are able to read data from other keys, so it's possible to construct rules that are based upon the existence of a key (i.e. membership of a team).

    What's below is a small fragment of the Bolt rules that I've used for a Firebase database:

    path /teams/{$teamKey}/members/{$userId} is Boolean {
        ...
    }
    
    path /users/{$userId}/shares/{$teamKey} {
        ...
        read() { root.teams[$teamKey].members[auth.uid] !== null }
    }
    

    The JSON would look something like this:

    ...
    "users": {
      "$userId": {
        ...
        "shares": {
          "$teamKey": {
            ...
            ".read": "root.child('teams').child($teamKey).child('members').child(auth.uid).val() != null",
            ...
    

    Hopefully, that will make some sense. Basically, there is a key for a team and it contains user ids (with boolean values). And read access to shared information under a user's key is granted to other team members by verifying their membership - that is, by checking for the existence of a user id key under the team key. Essentially, you store the data that drives the security rules in the database itself.

    You don't have to use Bolt, but I find it much easier to manage than the JSON representation. The Bolt language documentation contains information on the RuleDataSnapshot Methods for both the Bolt definitions and the JSON definitions.