Search code examples
firebasegoogle-cloud-firestoregeolocationgeofirestore

Secure and Filter certain data "Keys" inside the FireStore document


I am developing an application that needs to search all nearby users WITHOUT sharing their coordinates within 100 miles let's say. The example below I am using GeoHash to help me in calculating the distance.

In FireStore, I have the following document inside collection of users.

{
   "userId" : "12345",
   "displayName" : "username",
   "geoHash" : "gbsuv",
   "photoUrl" : "example.com/user.jpg",
   "refId" : "0001"
}

The question is: How should I protect the "geoHash" from being retrieved within each document inside the collection?


Solution

  • Firestore security rules grant access on a document level. So either the user can read an entire document, or they can't read anything in that document. There's no way to grant users access to only part of a document.

    This means that you can't query something that the client can't read. So in your current structure, if the user needs to query on geoHash, they will be able to read that field too.

    The only alternative is to not let the client do the querying, but instead do that querying on a server (such as in Cloud Functions). For this you'd store the geohash for each user in a separate document (say in a collection called locations). The Cloud Function then queries this collection, and returns the real user document(s) (which doesn't contain the geohash anymore) to the user.