0
votes

I am using Firebase Auth and read a lot of documentation on security rules, custom claims, cloud functions, but I've really gotten more confused.

Consider the following data structure

{
    "company": {
        "idCompany1": {"data": "Restricted to Company1s users"},
        "idCompany2": {"data": "Restricted to Company2s users"}
    },
    "users": {
        "idUser1": {
            "companies": {
                "idCompany1": true
            }
        },
        "idUser2": {
            "companies": {
                "idCompany1": true,
                "idCompany2": true
            }
        }
    }
}

I would like to implement a simple rule in the Firebase Console (Firebase Security Rule) without modifying my Data Structure.

The Rule I would like to configure is: A user can only read or write information in the companies to which it belongs (users/$idUser/companies/$idCompany === true on path company/$idCompany)

At this moment I have only configured:

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

How can I configure this Firebase security Rule in the Firebase Console?

1

1 Answers

1
votes

It sounds like you're looking for:

{
  "rules": {
    "company" : {
      "$companyid": {
        ".read": "root.child('users').child(auth.uid).child('companies').child($companyid).val() === true"
      }
    }
  }
}

This will allow the user to read /company/$companyid for any company where it is listed in their profile.

Note: you won't be able to read /company itself, as rules are not filters.