Reflekti0n
Reflekti0n

Reputation: 85

Firebase Database: add rule to find a particular value out of all childs

I want to setup security rules for my database and I want only the users and the admins to read from this particular group, but my rules don't work.

The only work when I set a specific index. I don't know how I can check all indexes. Is this possible in some way?

database: database

rules:

{
  "rules": {
    "groups": {
      "$groupid": {
        ".write": "!data.exists()",
        ".read": "data.child('users').child('$index').val() == auth.uid || data.child('admins').child('$index').val() == auth.uid"
      }
    },
    "users": {
      "$uid": {
        ".read": "auth != null",
        ".write": "$uid === auth.uid"
      }
    }  
  }
}

Upvotes: 0

Views: 262

Answers (1)

Wilik
Wilik

Reputation: 7720

I suggest you to change the database structure into something like this. Put the user's id as the child key of users and admins

{
    "groups": {
        <groupId1>: {
            "admins": {
                <uid1>: true,
                <uid2>: true
            },
            "description": "some description",
            "users": {
                <uid3>: true,
                <uid4>: true,
                <uid5>: true
            },
            ...
        },
        <groupId2>: {
            ...
        }
    }
}

Then this database rules will do the job

{
    "rules": {
        "groups": {
            "$groupid": {
                ".write": "!data.exists()",
                ".read": "data.child('users').child(auth.uid).val() == true || data.child('admins').child(auth.uid).val() == true"
            }
        }
    }
}

Hope this helps :)

Upvotes: 1

Related Questions