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

Bilal Soomro picture Bilal Soomro · Mar 12, 2017 · Viewed 10.6k times · Source

In the example below, is there a way to get the uid of the user who wrote to /messages/{pushId}/original?

exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onWrite(event => {
  // Grab the current value of what was written to the Realtime Database.
  const original = event.data.val();
  console.log('Uppercasing', event.params.pushId, original);
  const uppercase = original.toUpperCase();
  // You must return a Promise when performing asynchronous tasks inside a Functions such as
  // writing to the Firebase Realtime Database.
  // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
  return event.data.ref.parent.child('uppercase').set(uppercase);
});

Answer

jwngr picture jwngr · Mar 12, 2017

UPDATED ANSWER (v1.0.0+):

As noted in @Bery's answer above, version 1.0.0 of the Firebase Functions SDK introduced a new context.auth object which contains the authentication state such as uid. See "New properties for user auth information" for more details.

ORIGINAL ANSWER (pre v1.0.0):

Yes, this is technically possible, although it is not currently documented. The uid is stored with the event.auth object. When a Database Cloud Function is triggered from an admin situation (for example, from the Firebase Console data viewer or from an Admin SDK), the value of event.auth is:

{
  "admin": true
}

When a Database Cloud Function is triggered from an unauthenticated reference, the value of event.data is:

{
  "admin": false
}

And finally, when a Database Cloud Function is triggered from an authed, but not admin, reference, the format of event.auth is:

{
  "admin": false,
  "variable": {
    "provider": "<PROVIDER>",
    "provider_id": "<PROVIDER>",
    "user_id": "<UID>",
    "token": {
      // Decoded auth token claims such as sub, aud, iat, exp, etc.
    },
    "uid": "<UID>"
  }
}

Given the information above, your best bet to get the uid of the user who triggered the event is to do the following:

exports.someFunction = functions.database.ref('/some/path')
  .onWrite(event => {
    var isAdmin = event.auth.admin;
    var uid = event.auth.variable ? event.auth.variable.uid : null;

    // ...
});

Just note that in the code above, uid would be null even if isAdmin is true. Your exact code depends on your use case.

WARNING: This is currently undocumented behavior, so I'll give my usual caveat of "undocumented features may be changed at any point in the future without notice and even in non-major releases."