Diego
Diego

Reputation: 13

Firebase: How to grant permission to add new nodes but only the owner can modify them?

I have a problem with the Firebase rules.

I want to grant write access to the books node (add new books) only to authenticated users. Also, I want that a single book can be modified only by the owner of the book. This is my DB and my rules:

o- books 
  o- book1 
    o- owner : user1
    o- name : nice book
    o- pages { ... }
    o- users { ... }

  o- book2
    o- owner : user2
    o- name : other book
    o- pages { ... }
    o- users { ... }

And here the rules

{
  "rules": {
    "books": {
      ".write": "auth != null",
      "$bookId": {
        ".read": "data.child('users').hasChild(auth.uid)",
        "pages" : {
          ".write": "data.child('owner').val() == auth.uid"
        }
      }
    }
  }
}

The problem is that is granting the write operation in /books/book1 with the authenticated user2 because the first write (auth != null) is true...

I appreciate any help, Thank you very much.

Upvotes: 1

Views: 233

Answers (1)

adolfosrs
adolfosrs

Reputation: 9389

When you set the write access right under the books branch you will give write access for the users to write on whatever data under it. So I guess you are looking for something like the following:

{
  "rules": {
    "books": {
      "$bookId": {
        ".write": "newData.child('owner').val() == auth.uid && (!data.exists() || data.child('owner').val() == auth.uid)",
        ".read": "data.child('users').hasChild(auth.uid)"
      }
    }
  }
}

This will ensure that whatever change the user make it will have his uid on it. And also, if is not a new book it is a book owned by him.

Upvotes: 1

Related Questions