简体   繁体   中英

Firebase auth onUpdate cloud function for when a user updates their email

I need to run a Firebase function whenever my user updates their email address, except auth only has onCreate and onDelete. How can I react to email updates?

It's not possible today to directly react to an email address changing in Firebase Authentication. If you'd like to see that as a feature, please file a feature request .

You can react to it indirectly by having your app listen to authentication events ( Android ), take the User object delivered to your listener, and write the user's email address to a RealtimeDatabase location (or Firestore document) for that user's UID. Then, you can have a database trigger that tracks the location of your users in the database, and react to the change there.

正如 Doug Stevenson 所说,此功能尚未实现,因此您可以在 updatePhoneNimber 回调之后使用 Firestore 文档更新,然后在您的用户集合上使用 OnUpdate 或 OnWrite 触发此功能,例如通知您自己的后端服务器

"

My Workaround Use functions.https.onCall to create an HTTPS callable function.

Firebase Function

exports.onUpdateUserEmail = functions.https.onCall((data, context) => {
  const uid = context.auth.uid;
  const email = context.auth.token.email || null;
  return admin.
      firestore()
      .collection("users")
      .doc(uid)
      .set({email});
});

Deploy

$ firebase deploy --only functions:addMessage

Call your Fonction in your app nodejs example firebase v9

import { initializeApp } from 'firebase/app';
import { getAuth, updateEmail } from "firebase/auth";
import { getFunctions, httpsCallable } from 'firebase/functions';

 const app = initializeApp({
     projectId: '### CLOUD FUNCTIONS PROJECT ID ###',
     apiKey: '### FIREBASE API KEY ###',
     authDomain: '### FIREBASE AUTH DOMAIN ###',
   });
   const functions = getFunctions(app);
   const onUpdateEmail = httpsCallable(functions, 'onUpdateUserEmail');
   const auth = getAuth();
   updateEmail(auth.currentUser, "user@example.com").then(() => {
   // Email updated!
      onUpdateEmail();
   }).catch((error) => {
   // An error occurred
   // ...
});

If you're working with Firestore or RTDB, you could do the opposite trigger. When a user update's their "photoURL" in a users collection in Firestore, for example, it triggers a profile update in Firebase Auth.

This does not prevent the profile from being updated indirectly, but it does give you only one command to update.

Maybe one day there will be Firestore Auth Rules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM