0

I have a users collection which has documents containing various fields. Each document ID is the firebase user ID and the fields hold user data.

I am using the following rule:

match /databases/{database}/documents {
  // Make sure the uid of the requesting user matches name of the user document.
  match /users/{userId} {
    allow read, update, delete: if request.auth.uid == userId;
    allow create: if request.auth.uid != null;
  }
}

Users can select "favourite songs" which are saved within an array field. I now have a requirement to query the database for users which have added a certain songs to their favorites. I created the following query:

FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference usersRef = db.collection("users");
usersRef.whereArrayContains("favouriteSongs", "id_of_song");

When the query is run the following error is returned:

com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions.

I obviously need to alter my Firestore rule to allow a user to query the "favouriteSongs" field; however, I do not want to expose all user data to everyone.

Is there a way to expose the "favouriteSongs" data (which only holds IDs) and ensure the rest of the user collection is restricted from being read?

Thanks

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Michael J
  • 825
  • 1
  • 9
  • 18
  • If you want to expose only part of a document to a user, then DarkNeuron's answer is correct. I'm just wonder if you aren't actually for [how to securely query data](https://firebase.google.com/docs/firestore/security/rules-query). – Frank van Puffelen Sep 25 '20 at 14:17

1 Answers1

1

Sadly no, security rules are on document/query level. So if a security rule allows access, then the user will have access to the entire document.

If favouriteSongs is the only field that can/should be read publicly, then that field should be in a different document.

There are several options. You could have a root level collection called favoriteSongs with user documents in it only containing the public data. This would give you the flexibility to easily look up a user's favorites, or query across all the data to find how many users like a particular song.

I recommend that only the user itself can read it's own document, with regards to privacy etc (maybe GDPR if relevant).

DarkNeuron
  • 7,981
  • 2
  • 43
  • 48