firebase-realtime-databasefirebase-authenticationfirebase-security

Firebase Realtime Database Rules for collaboration between users on certain data


I am using Firebase Realtime Database. I am working on a new feature to allow one authenticated user to give access to another authenticated user so both can work on it.

The structure of the data is

{
  "dataTables": {
    "myUserId": {
      "2-15-2023": {
        "myTableId": {
          "description": "This table was auto generated to show you a demo of the application. You can leave it, edit it or delete it.",
          "name": "Demo 1 Past",
          "rows": {
            "-NLBD8RiJeyZpnKg8iKI": {
              "lastEdit": 1676495720665,
              "name": "This is a marked text.",
              "priority": 1
            },
            "-NLBD8RjFcXNKJEWFefR": {
              "lastEdit": 1676495720665,
              "name": "This is a regular task. Tasks can be edited by pressing the gear icon at the right side of a task.",
              "priority": 2,
              "status": 1
            }
        }
    }
}

The structure of the data that controls the access that a user has to other tables

{
  "sharedTables" {
    "myUserId": {
      "myTableId": {
        "data" : "data"
      }
    }
  }
}

The current rules for the database are the following:

"dataTables": {
  "$ownerUid": {
    ".read": "$ownerUid === auth.uid",  
    ".write": "$ownerUid === auth.uid",
    "$tableDate": {  
      "$tableId": {  
        ".read": "$ownerUid === auth.uid || root.child('sharedTables').child($ownerUid).child($tableId).exists()",
        ".write": "$ownerUid === auth.uid"
      }
    }
  }
}

With this rule, regular users can still access their data.

But when I try to access /dataTables/myUserId/2-15-2023/myTableId I am not allowed. Basically trying to access the table that I was given access to.

Can I access inside $ownerUid to $tableId from the nesting?

Am I going in the right direction?


Solution

  • This one below works perfectly. I have access to all my own tables under /dataTables/UID/TABLES. And I also have access to individual tables that are specified in /sharedTables

     "dataTables": {
      "$ownerUid": {
        ".read": "auth != null && auth.uid === $ownerUid",
        ".write": "auth != null && auth.uid === $ownerUid",
        "$tableDate": {
          "$tableId": {
            ".read": "auth != null && (auth.uid === $ownerUid || root.child('sharedTables').child(auth.uid).child($tableId).exists())",
            ".write": "auth != null && auth.uid === $ownerUid"
          }
        }
      }
    }