bonblow
bonblow

Reputation: 1189

Firebase Database - change value only by creator?

Is there a way to let only the creator of the room (by uid) change the value of ready? Maybe in rules? I've no clue.

room
    -L55EIcL2HfaGCKpKN9o
        creatorUid: "GCKpKjFHUccihC0ikxmXjnqO82"
        ready: false
        user
            -L55FCzXGL7IbPyNJXhI 
                uid: "GCKpKjFHUccihC0ikxmXjnqO82"
            -L55GK540811AQl0TDYt
                uid: "KRVpMnjjFHUccihC0C0ikxmXjF"

I tried:

{
  "rules": {
    ".read": true,
    ".write": true,
    "room": {
      "$ready": {
        ".write": "$creatorUid == auth.uid"
      }
    }
  }
}

But I get the error:

Line 10: Unknown variable '$creatorUid'.

Creating a room with following JS code:

let user = firebase.auth().currentUser
                let room = dbRoomRef.push()
                room.set({
                    creatorUid: user.uid,
                    creatorName: user.displayName,
                    ingame: false,
                    timestamp: firebase.database.ServerValue.TIMESTAMP
                })

Upvotes: 0

Views: 308

Answers (1)

Rosário P. Fernandes
Rosário P. Fernandes

Reputation: 11326

According to the documentation:

Shallower security rules override rules at deeper paths. Child rules can only grant additional privileges to what parent nodes have already declared. They cannot revoke a read or write privilege.

This means that the ".read":true and ".write":true will override any other rule you specify under the root node. So you might want to start by removing that ".write":true line.

The node under the "room" node is the roomID, not the ready child. The ready child is under the roomID, so you'll have to follow that structure:

{
  "rules": {
    ".read": true,
    "room": {
      "$roomID": {
        "ready":{
            ".write": "data.parent().child('creatorUid').val() == auth.uid"
        }
      }
    }
  }
}

Notice that I've used the parent() method in the rule to access the roomID node, then child() to access the creatorUid under that same node. Then I compare if it's value is equal to the auth.uid.

Upvotes: 2

Related Questions