Firestore - Cloud Functions - Get uid

I have been facing a similar issue. In Firebase, it was easy - you simply took the data from event.auth. I would assume this is simply a feature not implemented yet while we are in the beta phase of Firestore. Adding the user id to the path does not work as you previously mentioned as it will constantly be changing depending on the user making the update.

My scenario is that I want to create a "lastUpdatedBy" field in the object being updated. If we were to allow the client to send in a lastUpdatedBy field in the payload, this could be abused by a rogue client (i.e. someone with a authenticated account) trying to impersonate someone else. Therefore in Firebase we relied on a cloud function to populate this field on data change events.

My workaround is to allow the client to insert the "lastUpdatedBy" field but additionally use the Firestore rules to validate that the userId in the payload matches that of the logged in user - otherwise deny the write request.

Something like:

match /collectionA/{docId} {
  allow update: if request.resource.data.lastUpdatedBy == request.auth.uid;
}

Until Google/Firestore guys add the "auth" object to the cloud function I don't see any other workaround but would love to hear differently.


Since Cloud Functions 1.0 you can get the UID like this

exports.dbCreate = functions.database.ref('/path').onCreate((snap, context) => {
  const uid = context.auth.uid;
  const authVar = context.auth; 
});

Here is a nice post from the FB team for all CF1.0 changes: https://firebase.google.com/docs/functions/beta-v1-diff#event_parameter_split_into_data_and_context

The data of context.auth can be found here: https://firebase.google.com/docs/firestore/reference/security/#properties