有没有办法在更新用户节点时触发 Firebase 函数?

Is there a way to trigger a Firebase Function when the user node is updated?

我有两个包含用户关联电子邮件的节点。每当用户重置他们的身份验证电子邮件时,它都会在 Firebase 身份验证用户节点中更新,并通过扇出技术在我的数据库中更新两个附加节点。每次用户更新他们的身份验证电子邮件时,他们都会收到一封电子邮件地址更改通知,允许他们恢复电子邮件地址更改。

我 运行 遇到的问题是,如果用户恢复这些更改,正确的电子邮件地址将不再反映在数据库中,并且处于不一致的状态。我的解决方案是让这些节点在用户更改其身份验证电子邮件时通过 Cloud Function 自动更新。

这可能吗?如果是这样,我将用什么来实现它?如果没有,是否有任何人知道的另一种解决方法可以使我的数据库保持身份验证电子邮件更改的一致状态?

经过几个小时的调查,我发现这可以通过 Firebase Admin SDK 实现。有关详细信息,请参阅 https://firebase.google.com/docs/auth/admin/manage-users

基本上,您创建了一个 Cloud Function,它使用管理 SDK 重置电子邮件,而不向用户发送讨厌的通知,成功后,使用服务器端扇出更新数据库。

例如:

const functions = require('firebase-functions');
const admin = require("firebase-admin");
// Initializes app when using Firebase Cloud Functions 
admin.initializeApp(functions.config().firebase);
const databaseRef = admin.database().ref();


exports.updateEmail = functions.https.onRequest((request, response) 
    // Cross-origin headers
    response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
    response.setHeader("Access-Control-Allow-Origin", "YOUR-SITE-URL");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");

    const email = request.body.email;
    const uid = request.body.uid;

    // Update auth user
    admin.auth().updateUser(uid, {
        "email": email
    })
    .then(function() {
        // Update database nodes on success

        let fanoutObj = {};
        fanoutObj["/node1/" + uid + "/email/"] = email;
        fanoutObj["/node2/" + uid + "/email/"] = email;

        // Update the nodes in the database
        databaseRef.update(fanoutObj).then(function() {
            // Success
            response.send("Successfully updated email.");
        }).catch(function(error) {
            // Error
            console.log(error.message);
            // TODO: Roll back user email update
            response.send("Error updating email: " + error.message);
        });
    })
    .catch(function(error) {
        console.log(error.message);
        response.send("Error updating email: " + error.message);
    });
});

此技术可用于在您之后必须执行某些任务的情况下更改用户信息,因为 Firebase 还没有在用户个人资料数据更改时运行的 Cloud Function 触发器,正如 Doug Stevenson 所指出的在评论中。