0
votes

I am coding a microblogging site on Firebase, to which I am very new. I am storing user information (e.g. introduction, profile pictures) and posts the users write like below structure:

{
  "posts" : {
    "postid" : {
      "category": "xx",
      "content": "xx",
      "uid":"xx"
  }
  },
  "users" : {
    "uid" : {
      "intro" : "xx",
      "nickname" : "xx",
      "profile_picture" : "xx"
      }
  }
}

I'd like make following rules:

  1. Any signed-in users will be able to post, but only will be able to edit their own posts afterwards

  2. For user info, they will only be able to post/edit their own.

I set the database security rules like below.

"users": {
  ".read": true,
  "$uid": {
      ".write": "auth.uid===$uid"
  },
},
"posts": {
  ".read": true,
  ".write": "auth!==null",
},

Here are a couple of issues:

a. This rule will enable any bad user to edit any other post that is not his/her own.

b. When trying to write to users node, there is no existing UID child node at the moment and the users are denied permission to write.

How can I change the database rules to solve the two issues? My preference is doing so without rewriting the front-end code or change the database structure...would love to seek some advice here!

1
You've included links to pictures of the JSON tree and security rules in your question. Please replace that with the actual JSON and rules as text. For the JSON you can easily get this by clicking the Export JSON link in the overflow menu (⠇) of your Firebase Database console. Having the JSON and rules as text makes them searchable, allows us to easily use them to test with your actual data and rules and use them in our answer and in general is just a Good Thing to do. - Frank van Puffelen
Hi @FrankvanPuffelen, thanks for the advice for a web development newbie. I changed the contents as you suggested. Could you take a look? Thanks! - J.Ko

1 Answers

0
votes

To only allow users to write their own posts (or create new posts with their own UID), you can check the value of the uid field in write operations:

"posts": {
  ".read": true,
  ".write": "auth !== null && auth.uid === newData.child('uid').val",
},