Eduardo Rodriguez
Eduardo Rodriguez

Reputation: 172

Firebase DB - Allow access on collection nodes just for owner users

I want to know if my problem could be solved using firebase DB rules, this is the question:

How can I write rules to make firebase just respond the requests related to an authenticated user?

I have 2 collections users and requests. Each user has a requests object and each requests object has a users object in order to connect both collections. A request is related to two users.

bellow are the structures

{
"users": {
    "user1": {
        "requests": {
            "req1": true,
            "req2": true
        }
    },
    "user2": {
        "requests": {
            "req1": true
        }
    }
},
"requests": {
    "req1": {
        users: {
            user1: true,
            user2: true
        }
    },
    "req2": {
        users: {
            user1: true,
            user3: true
        }
    }
}}

I have a rule to .read/.write, but this works only if I request to /requests/someId:

{
  "requests": {
    "$request_id": {
      ".read": "data.child('users').hasChild(auth.uid)",
      ".write": "data.child('users').hasChild(auth.uid)"
}}

I've been trying lots of combinations of rules but I cannot get just the requests related to a user when I ask for /requests

Upvotes: 2

Views: 64

Answers (1)

p3sn
p3sn

Reputation: 1072

You can't use rules to 'filter' results. You can only send a query to nodes of the database where this user has access to.

The solution is to split things up. Let's say you have a collection with these keys: A, B, C, D, E, F, G

For user ER4521, you need to make a node ER4521/collection with as content: B, D, F, G

First request would be to get the collection if ER4521/collection And then send a request for each result to get all information about B, D, F and G.

Or you're going to use cloud functions which duplicates a collection to the userid/collection.

Regards, Peter

Upvotes: 1

Related Questions