0
votes

I have a question about the firebase realtime database rules.

Somebody creates an account and that account creates a path in the realtime database:

The structure is simple (key, userid, other data).

enter image description here

This are my rules:

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {

    "waitingForApproval": {
      "$uid": {
        ".write": true,
        ".read": "auth != null && $uid === auth.uid"
      }
    },
  }
}

But now comes the question. How can I allow to let users write to this object? Everyone who has the code (see BQUyhq)w3D) can write to the object id. They can't write to it when they don't have the code.

Is something possible like that? If so, how can I do that.

1

1 Answers

0
votes

I can think of two ways to approach something like this:

1. Using a cloud function:

Set the rule for writing to false and use a cloud function to make updates. The cloud function would take the code as an input, verify it matches the expected code, and perform the updates on the user's behalf. E.g.:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

exports.updateObject = functions.https.onCall((data, context) => {
  const uid = data.uid;
  const code = data.code;

  const codeRef = admin.database().ref(`waitingForApproval/${uid}/code`);
  return codeRef.once('value').then((codeSnapshot) => {
    if (codeSnapshot.val() === code) {
      // Make updates on the user's behalf
    }
  });
});

2. Storing user entered code in the DB:

Add a user editable section where users can set their codes and validate against that, e.g.:

The DB after a user has entered a code:

"userCodes": {
  "bXUQ6PRNqvOgjwoAlm6HmYuWiYo1": {
    "BQUyhq)w3D": true,
  },
  ...
}

Set your rule to check if the user has set the code for the object:

"waitingForApproval": {
  "$uid": {
    ".write": "root.child('userCodes').child($uid).child(data.child('code').val()).val() == true"
    ".read": "auth != null && $uid === auth.uid"
  }
},

Which essentially checks if userCodes/{uid}/{code} is set to true before allowing the write.

(Note that using this method your codes cannot contain the characters that firebase doesn't support in its keys: . $ # [ ] /)