云功能触发文档更新

时间:2020-07-07 23:24:12

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

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

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

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)
          })
      }
    })
  }
})

现在该功能没有触发,有什么想法吗?

2 个答案:

答案 0 :(得分:1)

Cloud Functions中的

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

尚不清楚您希望该代码对用户执行什么操作,但是如果要检查路径中uid的用户是否具有已验证的电子邮件地址,则可以load that user by their UID借助Admin SDK。

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

答案 1 :(得分:1)

我支持弗兰克所说的话。

您可以通过admin方式获取用户:

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