Getting the user id from a Firestore Trigger in Cloud Functions for Firebase?
I was struggling on this for a while and finally contacted the firebase Support:
The event.auth.uid
is undefined in the event object for firestore database triggers. (It works for the realtime Database Triggers)
When I console.log(event)
I can’t find any auth
in the output.
The official support answer:
Sorry the auth is not yet added in the Firestore SDK. We have it listed in the next features.
Keep an eye out on our release notes for any further updates.
I hope this saves someone a few hours.
UPDATE:
The issue has been closed and the feature will never be implemeted:
Hi there again everyone - another update. It has been decided that unfortunately native support for context.auth for Firestore triggers will not be implemented due to technical constraints. However, there is a different solution in the works that hopefully will satisfy your use case, but I cannot share details. On this forum we generally keep open only issues that can be solved inside the functions SDK itself - I've kept this one open since it seemed important and I wanted to provide some updates on the internal bugs tracking this work. Now that a decision has been reached, I'm going to close this out. Thanks again for everyone's patience and I'm sorry I don't have better news. Please use the workaround referenced in here.
Summary of how I solved this / a workable solution:
On client
Add logged in/current user's uid (e.g. as creatorId
) to entity they're creating. Access this uid by storing the firebase.auth().onAuthStateChanged()
User object in your app state.
In Firebase Firestore/Database
Add a Security Rule to create
to validate that the client-supplied creatorId
value is the same as the authenticated user's uid; Now you know the client isn't spoofing the creatorId
and can trust this value elsewhere.
e.g.
match /entity/{entityId} {
allow create: if madeBySelf();
}
function madeBySelf() {
return request.auth.uid == request.resource.data.creatorId;
}
In Firebase Functions
Add an onCreate
trigger to your created entity type to use the client-supplied, and now validated, creatorId
to look up the creating user's profile info, and associate/append this info to the new entity doc.
This can be accomplished by:
-
Creating a
users
collection and individualuser
documents when new accounts are created, and populating the newuser
doc with app-useful fields (e.g.displayName
). This is required because the fields exposed by the Firebase Authentication system are insufficient for consumer app uses (e.g.,displayName
andavatarURL
are not exposed) so you can't just rely on looking up the creating user's info that way.e.g. (using ES6)
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
const APP = admin.initializeApp()
export const createUserRecord = functions.auth.user()
.onCreate(async (userRecord, context) => {
const userDoc = {
id: userRecord.uid,
displayName: userRecord.displayName || "No Name",
avatarURL: userRecord.photoURL || '',
}
return APP.firestore().collection('users').doc(userRecord.uid).set(userDoc)
})
- Now that you have a validated
creatorId
value, and usefuluser
objects, add anonCreate
trigger to your entity type (or all your created entities) to look up the creating user's info and append it to the created object.
export const addCreatorToDatabaseEntry = functions.firestore
.document('<your entity type here>/{entityId}')
.onCreate(async (snapshot, context) => {
const userDoc = await APP.firestore().collection('users').doc(snapshot.data().creatorId).get()
return snapshot.ref.set({ creator: userDoc.data() }, { merge: true })
})
This clearly leads to a lot of duplicated user info data throughout your system -- and there's a bit of clean up you can do ('creatorId` is duplicated on the created entity in the above implementation) -- but now it's super easy to show who created what throughout your app, and appears to be 'the Firebase way'.
Hope this helps. I've found Firebase to be super amazing in some ways, and make some normally easy things (like this) harder than they 'should' be; on balance though am a major fan.
Until this is added to firestore functions a workaround is to add the user_id
as a field when creating a document then deleting after. You can then grab it in the function onCreate then after you use it for what you need it for, while still in the function, just delete the field from that document.
The documentation states clearly that the context.auth
param is only available in the Realtime Database.
This field is only populated for Realtime Database triggers and Callable functions. For an unauthenticated user, this field is null. For Firebase admin users and event types that do not provide user information, this field does not exist.
Personally I realized that I had the userId already in the path of my data.
export const onCreate = functions.firestore.document('docs/{userId}/docs/{docId}')
.onCreate((snapshot, context) => {
const userId = context.params.userId;