How can determine the authenticated user who made the change within a Firestore 2nd gen trigger?
The 1st gen onUpdate
trigger provides a change object & a context object where you can get the auth. The equivalent 2nd gen onDocumentUpdated
instead only provides an event object which doesn't appear to include the auth
user.
1st gen
export const onUserUpdate = Firestore
.document("users/{userId}")
.onUpdate(async (change, context) => {
const before = change.data.before.data();
const after = change.data.after.data();
// Access the authenticated user information
const user = context.auth;
if (user) {
console.log("Authenticated user ID:", user.uid);
console.log("Authenticated user email:", user.token.email);
console.log("Authenticated user name:", user.token.name);
// You can access more user properties as needed
} else {
console.log("No authenticated user information available.");
}
});
2nd gen
exports.onUserUpdate = onDocumentUpdated("user/{userId}", async (event) => {
const before = event.data.before.data();
const after = event.data.after.data();
// how do I get auth?
});
event: FirestoreEvent<Change<QueryDocumentSnapshot>
https://firebase.google.com/docs/functions/firestore-events?gen=2nd
The 1st gen onUpdate trigger provides a change object & a context object where you can get the auth.
Actually, you can't get the user from that v1 context. See:
And you still can't with v2 triggers.
You are welcome to send your feedback to Firebase support about this, but I doubt anything will change soon as it's been over 5 years of people asking for this.
While doug is correct with the Firebase API and the likeliness of any changes
I suggest providing a context
or operation
field to the document that contains all the essential data you need. with this, you can check the document data on this path field, and enforce it with security rules.
for example:
event.data.after.data().context
should contain the new user who made the changes
while
event.data.before.data().context
would contain information about the previous user
and due to the way firebase handles triggers, these should fire incrementally, best used with transactions but not required if you use security rules correctly. this can be further enhanced with additional fields to monitor updates and other rate limiting properties that you can validate with security rules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With