【问题标题】:Cloud function trigger on document update文档更新时的云功能触发
【发布时间】:2020-07-07 23:24:12
【问题描述】:

如果users/{userId} 上有文档更新,我正在尝试启动我的云功能

我有一个每次用户登录时都会触发的登录方法

signin: (email, password, setErrors) => {
    firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(() => {
        const isVerified = firebase.auth().currentUser.emailVerified
        const userUid = firebase.auth().currentUser.uid
        const db = firebase.firestore()
        if (isVerified) {
          db.collection('/users')
            .doc(userUid)
            .update({ isVerified: true })
        }
      })
      .catch(err => {
        setErrors(prev => [...prev, err.message])
      })
  },

没什么特别的,除了基本的登录内容外,它还会检查用户是否验证了他们的电子邮件,如果验证通过,它将更新该用户的集合。这里的一切都按预期工作。

但是我似乎无法启动我的云功能。

基本上,它正在监听user 集合上的变化。如果users/{userId} 文档有isVerified 并且用户电子邮件地址以xxxx 结尾,它应该授予他们管理员权限。

exports.updateUser = functions.firestore.document('users/{userId}').onUpdate((change, context) => {
  const after = change.after.data()
  if (after.isVerified) {
    firebase.auth().onAuthStateChanged(user => {
      if (user.emailVerified && user.email.endsWith('@xxxx')) {
        const customClaims = {
          admin: true,
        }
        return admin
          .auth()
          .setCustomUserClaims(user.uid, customClaims)
          .then(() => {
            console.log('Cloud function fired')
            const metadataRef = admin.database().ref('metadata/' + user.uid)
            return metadataRef.set({ refreshTime: new Date().getTime() })
          })
          .catch(error => {
            console.log(error)
          })
      }
    })
  }
})

现在函数没有触发,有什么想法吗?

【问题讨论】:

  • 它可能正在触发,只是没有进入那么大的 if() {...} 你怎么知道它没有触发?你检查你的函数日志并检查它是否没有触发?
  • 是的,我做了,日志是空的
  • 在 if (after.isVerified) {} 之前放置一个日志,然后重试。类似于 console.info(JSON.stringify(after))
  • 好的,看起来它正在触发,但代码块(after.isVerified)没有执行......我是否有可能无法使用 firebase.auth() 检索用户?跨度>
  • 确实是这个问题。我会写一个答案。

标签: node.js firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

Cloud Functions 中的代码作为管理帐户运行,无法使用常规 Firebase 身份验证 SDK 进行检索。事实上,您应该只在 Cloud Functions 代码中使用 Firebase Admin SDK,其中不存在 onAuthStateChanged 方法。

目前尚不完全清楚您希望这段代码对用户做什么,但如果您想检查路径中uid 的用户是否有经过验证的电子邮件地址,您可以使用Admin SDK load that user by their UID .

为确保路径中的uid 是执行操作的用户的真实UID,您可以使用安全规则,如securing user data 上的文档中所示。

【讨论】:

  • 我正在尝试向特定用户授予管理员访问权限,我真的不希望在客户端完成此操作,因此我选择了云功能。一旦用户验证了他们的电子邮件地址,上述方法就会执行,如果地址以 xxx 结尾,则授予管理员访问权限 - 我不确定这是否是最好的方法,但我只需要一种安全的方式来授予管理员访问权限,基于 currentUser.props
  • 这就是我在回答中所描述的:您可以使用 Admin SDK 来查找用户的属性。我添加了关于如何使用安全规则来确保 UID 正确的说明。
【解决方案2】:

我支持弗兰克所说的。

您可以通过这种方式获取具有管理员权限的用户:

if (after.isVerified) {
  admin.auth().getUser(userId)
    .then((userData) => { ... 

【讨论】:

    猜你喜欢
    • 2019-09-09
    • 1970-01-01
    • 2019-05-05
    • 2019-08-07
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    相关资源
    最近更新 更多