从Cloud Functions for Firebase中的数据库触发器获取用户标识?

Bil*_*mro 30 javascript firebase firebase-realtime-database google-cloud-functions

在下面的示例中,有没有办法获取写入/ messages/{pushId}/original的用户的uid?

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);
});
Run Code Online (Sandbox Code Playgroud)

jwn*_*ngr 50

更新的答案(v1.0.0 +):

正如上面@ Bery的回答所述,1.0.0Firebase Functions SDK的版本引入了一个新context.auth对象,其中包含身份验证状态,如uid.有关详细信息,请参阅"用户身份验证信息的新属性".

原始答案(pre v1.0.0):

是的,这在技术上是可行的,尽管目前没有记录.该uid存储与所述event.auth对象.从管理员情境(例如,从Firebase控制台数据查看器或管理SDK)触发数据库云功能时,值为event.auth:

{
  "admin": true
}
Run Code Online (Sandbox Code Playgroud)

从未经身份验证的引用触发数据库云功能时,值为event.data:

{
  "admin": false
}
Run Code Online (Sandbox Code Playgroud)

最后,当从authed而不是admin引用触发数据库云功能时,格式event.auth为:

{
  "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>"
  }
}
Run Code Online (Sandbox Code Playgroud)

鉴于上述信息,获得uid触发事件的用户的最佳选择是执行以下操作:

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

    // ...
});
Run Code Online (Sandbox Code Playgroud)

只要注意,在上面的代码,uidnull即使isAdmintrue.您的确切代码取决于您的使用案例.

警告:这是目前没有文档记录的行为,所以我会给出我一贯的警告:"未来的任何时候都可能会在未经通知的情况下更改未记录的功能,甚至在非主要版本中也会发生变化."

  • 为什么没有公共API的原因?看起来像一个合理的用例(我们正在探索FB作为后端,这是一个重要的突出问题). (5认同)
  • 有迹象表明这会改变或停留吗?这对我的用例来说是理想的,但如果仍然可以改变,我不想使用它. (4认同)
  • 添加了一个错误/请求来记录这个并使其成为官方公共API https://github.com/firebase/firebase-functions/issues/133 (3认同)

Ber*_*ery 12

自Firebase功能达到1.0版本以来,此行为不再是未记录的,但已经轻微改变.一定要阅读文档.

已将上下文添加到云功能中,您可以像这样使用它

  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.
  // ...
});
Run Code Online (Sandbox Code Playgroud)

  • 这个功能在 Cloud Functions 2.0 版本中似乎又消失了 (2认同)