1

TLDR: How can I set up the DB access rules so that I can read all the items I have authorization to from a given endpoint?

I have a similar set of data in my Firebase database:

"employees" : [ {
    "first_name" : "Constance",
    "last_name" : "Smith",
    "createdBy: "vdBoGzI2i9f12er6ZcPjG9AiTip2"
  }, {
    "first_name" : "Agatha",
    "last_name" : "Carlton",
    "createdBy: "Tpg1mFR99meDV2QGT44pU6y7s1T2"
  },
  ...
}

I also have a list of application users:

  "users" : {
    "Tpg1mFR99meDV2QGT44pU6y7s1T2" : {
      "name" : "Alex Lund",
      "isAdmin": true
    },
    "vdBoGzI2i9f12er6ZcPjG9AiTip2" : {
      "name" : "David Peterson",
      "isAdmin": false
    },
    ...
  },

Basic users will have access just to the employees they created; the admin will be able to read everything.

{
  "rules": {
    ".write": "auth != null",
    "employees": {
      "$employee": {
        ".read": "root.child('users').child(auth.uid).child('isAdmin').val() === true || data.child('createdBy').val() === auth.uid" 
      }
    },
}

With this rules, an admin will be able to read ref.child('/employees/0'), but won't have access to ref.child('employees').

How can I get all the employees I have read access to? Is running a query the only solution?

AL.
  • 36,815
  • 10
  • 142
  • 281
davidey
  • 35
  • 5

1 Answers1

0

With the rules as you have them now, a query on /users won't work. Since you don't have read permission on /employees any listener on that location will immediately be rejected.

You probably want the rules to be like this:

{
  "rules": {
    ".write": "auth != null",
    "employees": {
      ".read": "root.child('users').child(auth.uid).child('isAdmin').val() === true"
      "$employee": {
        ".read": "data.child('createdBy').val() === auth.uid" 
      }
    },
}

With these rules administrators can read (and thus query) /users, while regular users can only access children that they created.

This is a common pitfall when it comes to Firebase Database security rules and is typically referred to as "rules are not filters". See the relevant section in the documentation, this original Q&A on it and any of the questions in this list.

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807