Getting the User Id from a Database Trigger in Cloud Functions for Firebase

Getting the user id from a database trigger in Cloud Functions for Firebase?

Ever since Firebase functions reached version 1.0, this behavior is no longer undocumented but has sligtly changed. Be sure to read the docs.

Context has been added to cloud functions and you can use it like this

  exports.dbWrite = functions.database.ref('/path/with/{id}').onWrite((data, context) => {
const authVar = context.auth; // Auth information for the user.
const authType = context.authType; // Permissions level for the user.
const pathId = context.params.id; // The ID in the Path.
const eventId = context.eventId; // A unique event ID.
const timestamp = context.timestamp; // The timestamp at which the event happened.
const eventType = context.eventType; // The type of the event that triggered this function.
const resource = context.resource; // The resource which triggered the event.
// ...
});

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:

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.

Firebase first login cloud function trigger

I can't figure out how I have it trigger only on the first login, not when the user logs in for the second time and also not upon user creation

What you're trying to do is not possible with Cloud Functions auth triggers.

Auth triggers only work when a user account is created or deleted. They don't trigger when a user signs in. Only your app knows when a user signs in or out - neither Firebase Auth nor Cloud Functions understands your specific definition of what a "first sign in" actually means. What you will have to do is detect your "first sign in" in your app code, then possibly call a function (HTTP or callable) to do some work on behalf of the user.

Getting id of the current user from Cloud Functions and Firebase

You seem very new to JavaScript (calling it JSON is sort-of a give-away for that). Cloud Functions for Firebase is not the best way to learn JavaScript. I recommend first reading the Firebase documentation for Web developers and/or taking the Firebase codelab for Web developer. They cover many basic JavaScript, Web and Firebase interactions. After those you'll be much better equipped to write code for Cloud Functions too.

Now back to your question: there is no concept of a "current user" in Cloud Functions. Your JavaScript code runs on a server, and all users can trigger the code by writing to the database.

You can figure out what user triggered the function, but that too isn't what you want here. The user who triggered the notification is not the one who needs to receive the message. What you want instead is to read the user who is the target of the notification.

One way to do this is to read it from the database path that triggered the function. If you keep the notifications per user in the database like this:

user_notifications
$uid
notification1: ...
notification2: ...

You can trigger the Cloud Function like this:

exports.sendPushNotification = functions.database.ref('/user_notification/{uid}/{id}').onWrite(event => {

And then in the code of that function, get the UID of the user with:

var uid = event.params.uid;

Firestore - Cloud functions - Get uid of user who deleted a document

  1. Don't delete the document at all. Just add a field called "deleted", set it to true, and add another field with the UID of the user that deleted it. Use these new fields in your queries to decide if you want to deal with deleted documents or not for any given query.

  2. Use a different document in a separate collection that records deletions. Query that collection whenever you need to know if a document has been deleted. Or create a different record in a different database that marks the deletion.

There are really no other options. Either use the existing document or create a new document to record the change. Existing documents are the only things that can be queried - you can't query data that doesn't exist in Firestore.

How to get the uid of the authenticated Firebase user in a Cloud Functions storage trigger

Currently, with Cloud Storage triggers, you don't have access to authenticated user information. To work around that, you'll have to do something like embed the uid in the path of the file, or add the uid as metadata in the file upload.

Firebase Cloud Functions - How to get user that uploads a file?

You can upload custom metadata as an object containing String properties:

From documentation here:

var metadata = {
customMetadata: {
'location': 'Yosemite, CA, USA',
'activity': 'Hiking'
}
}

Then you can use getMetadata on the file (the doc here) to retrieve its information or for example get customMetadata like in my trigger function below.

For example and from my iOS application, I created a StorageMetadata and I set the customMetadata to ["user":"userID_AZERRRRR"]

In my node js functions, I developed the trigger function like this:

exports.testStorageOnFinalize = functions.storage.object().onFinalize(uploadedObject => {
console.log('metadata keys', Object.keys(uploadedObject.metadata));
console.log('metadata user', uploadedObject.metadata['user']);
})

In my log console:

3:00:20.140 PM info testStorageOnFinalize metadata user userID_AZERRRRR

Risks

From Doug comment, this solution is not fully secure because the meta data could be faked.

So, to resolve this, we can use the security rules for storage in order to check if the user is equal to identified user:

// Allow reads if a certain metadata field matches a desired value
allow read: if resource.metadata.user == request.auth.uid;

You can check storage rules here



Related Topics



Leave a reply



Submit