Search code examples
firebasefirebase-realtime-databasefirebase-security

Using Security Rules in Firebase to Limit Access in a Social Media App


I am implementing a social media app where people make posts and others can upvote/downvote them. I am using Firebase Realtime Database. I want authenticated users to be able to add posts and change the score of other posts by upvoting or downvoting but I don't want them to be able to change the contents of or delete other posts. Is there a way to give users access to add new posts without letting them change existing posts? Also is there a way to make sure that when users change the score of a post they only increment or decrement it? I was thinking of doing something like this but it doesn't work:

{
  "rules": {
    ".read": "auth.uid !== null",
    "posts": {
      ".write": "auth.uid !== null",
      "$postID": {
        "$score": {
            ".validate": "newData.isNumber() && (newData.val() == $score + 1 || newData.val() == $score - 1)" 
        }  
      }
    }
  }
}

Solution

  • please limit yourself to one question per post

    is there a way to make sure that when users change the score of a post they only increment or decrement it?

    Yes that is possible, but in your code you're comparing newData.val() (the new value) to $score, which is the key (string) of the node. You'll want to compare against data.val() instead, so:

    ".validate": "newData.isNumber() && (
        newData.val() == data.val() + 1 || 
        newData.val() == data.val() - 1
    )" 
    

    Note btw that .validate rules are not evaluated when a node is deleted, so you might want to do this in the .write rule if it should also prevent deletes.