Prevent users from modifying data in Firebase but

2019-08-20 18:09发布

问题:

I create an app with GatsbyJS (React) + Firebase.

Users have a score saved in Firebase Realtime Database with their data.

{
  users: {
    $uid: {
      score: 10,
      name: "Antho",
      ...
    }
  }
}

I do not want users to be able to change their score themselves, so I split my database like this:

{
  users: {
    $uid: {
      name: "uciska",
      ...
    }
  },
  scores: {
    $uid: {
      score: 10
    }
  }
}

But I do not know what rules to put in place.

I think I need some backend code. If so I would like to go through Amazon Lambda functions without having to set up a Node.js server.

Is it possible ? Where to start ?

Could Cloud Firestore do that more simply?

回答1:

If you don't want your user to be able to write the scores, you can simple use these rules:

{
  "rules": {
    "users": {
      "$uid": {
        ".write": "auth.uid == $uid"
      }
    }
    "scores": {
      ".write": false // this is not strictly needed, since the default is false
    }
  }
}

With this, each user can write their own node under /users/$uid and no user can write any score.

Next, you'll want to use the Firebase Admin SDK in a trusted environment to write the scores. A trusted environment is something you control access to, such as a server, your development machine, or Cloud Functions. Code that runs in Cloud Functions, or otherwise uses the Admin SDK, has administrative privileges, which means it bypasses the security rules. So that code can read/write the entire database, including the scores.