longlifelearner
longlifelearner

Reputation: 195

Firestore: remove sensitive fields on documents

I'm trying to figure it out how to remove a sensitive field on a firestore document. For example, my collection is a group information. The group is protected with a pin code field. Any one wants to join the group has to know the pin code.

In the meantime, I want to let users query what group is available to join. For query part, I don't want return group information with pin code information. Do we have anyway to remove sensitive fields from a document for Firestore for reading event?

Cloud function only supports write event. 1 possible solution is use cloud function on write event, and put pin code in a separate document. Is there a better solution? THanks.

My group schema is:

group: {
    name: string,
    pinCode: string
}

Upvotes: 3

Views: 1347

Answers (2)

Simone Bianchin
Simone Bianchin

Reputation: 1

You can create a Firebase Function that returns only the fields that you need (non sensitive), here an example:

exports.getTopUsers = functions.https.onCall(async (data) => {
   const users = [];
   return db.collection('users').orderBy('bids').limit(data.limit).get()
   .then((querySnapshot) => {
      querySnapshot.forEach((user) => {
         users.push({
            diplayName: user.get('displayName'),
         });
      });
      return {
         topUsers: users,
      };
   })
   .catch((err) => {
      console.error(err);
   });
});

So, you need to create a separate array (that will be returned) and filling it with only the field that you want while iterating your Firestore collection.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 599601

A user can either access a document, or they can't. There is no property-level access control in Firestore.

So to accomplish what you want, you will need to store the public and private information in separate documents.

You could either create a second document with the private information in the same collection and then secure them using:

match /databases/{database}/documents {
    match /groups/{group} {
      allow read: if resource.data.visibility != "private"
    }
}

Alternatively (and simpler to secure) you could create a separate collection for the private documents.

Upvotes: 3

Related Questions