问题
I have two nodes that contain a user's associated email. Whenever the user resets their authentication email, it is updated in the Firebase Authentication user node, as well as two additional nodes in my database via a fan-out technique. Each time a user updates their Authentication email they're sent an email address change notification which allows them to revert the email address change.
The problem I am running into is that if a user reverts these changes, the proper email address is no longer reflected in the database and it's left in an inconsistent state. My solution would be to have these nodes automatically updated via Cloud Function whenever a user changes their authentication email.
Is this possible? If so, what would I use to implement it? If not, is there another workaround that anyone knows of to keep my database in a consistent state for Authentication email changes?
回答1:
After quite a few hours of sleuthing, I have figured out that this is possible through the Firebase Admin SDK. See https://firebase.google.com/docs/auth/admin/manage-users for more details.
Basically, you make a Cloud Function which uses the admin SDK to reset the email without sending that pesky notification to the user and, on success, uses sever-side fan out to update the database.
For example:
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);
});
});
This technique can be used to do user information changes in cases where you have to perform some task afterwards, since Firebase does not yet have a Cloud Function trigger which runs when a user's profile data changes, as noted by Doug Stevenson in the comments.
来源:https://stackoverflow.com/questions/45871964/is-there-a-way-to-trigger-a-firebase-function-when-the-user-node-is-updated