Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the user id from a Firestore Trigger in Cloud Functions for Firebase?

Tags:

In the example bellow, is there a way to get the user id (uid) of the user who wrote to 'offers/{offerId}'? I tried to do as described here but it doesn't work in Firestore.

exports.onNewOffer = functions.firestore   .document('offers/{offerId}')   .onCreate(event => {     ... }); 
like image 283
Gabriel Bessa Avatar asked Oct 24 '17 13:10

Gabriel Bessa


People also ask

How do I trigger a Firebase cloud function?

Cloud Firestore triggersonCreate : triggered when a document is written to for the first time. onUpdate : triggered when a document already exists and has any value changed. onDelete : triggered when a document with data is deleted. onWrite : triggered when onCreate, onUpdate or onDelete is triggered.

How do I get specific data from firestore?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.


2 Answers

I was struggling on this for a while and finally contacted the firebase Support:

I was trying to achieve this.

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.

like image 81
Tim Avatar answered Sep 20 '22 20:09

Tim


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:

  1. Creating a users collection and individual user documents when new accounts are created, and populating the new user 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 and avatarURL 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)   }) 
  1. Now that you have a validated creatorId value, and useful user objects, add an onCreate 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.

like image 37
Ethan Avatar answered Sep 22 '22 20:09

Ethan