Benutzerdefinierte E-Mail-Aktions-Handler erstellen

Einige Aktionen zur Nutzerverwaltung, z. B. die Aktualisierung der E-Mail-Adresse eines Nutzers und das Zurücksetzen seines Passworts, führen dazu, dass E-Mails an den Nutzer gesendet werden. Diese E-Mails enthalten Links, über die die Empfänger die Nutzerverwaltungsaktion abschließen oder abbrechen können. Standardmäßig sind E-Mails zur Nutzerverwaltung mit dem Standard-Aktions-Handler verknüpft. Dabei handelt es sich um eine Webseite, die unter einer URL in der Firebase Hosting-Domain Ihres Projekts gehostet wird.

Sie können stattdessen einen benutzerdefinierten E-Mail-Aktions-Handler erstellen und hosten, um eine benutzerdefinierte Verarbeitung durchzuführen und den E-Mail-Aktions-Handler in Ihre Website einzubinden.

Für die folgenden Aktionen zur Nutzerverwaltung muss der Nutzer die Aktion mit einem E-Mail-Aktions-Handler ausführen:

  • Passwörter zurücksetzen
  • Widerruf von Änderungen an E-Mail-Adressen: Wenn Nutzer die primäre E-Mail-Adresse ihres Kontos ändern, sendet Firebase eine E-Mail an ihre alten Adressen, mit der sie die Änderung rückgängig machen können.
  • E-Mail-Adressen bestätigen

Um den E-Mail-Aktions-Handler Ihres Firebase-Projekts anzupassen, müssen Sie eine Webseite hosten, die das Firebase JavaScript SDK verwendet, um die und schließen Sie die Anfrage ab. Anschließend müssen Sie Firebase E-Mail-Vorlagen des Projekts eine Verknüpfung zu Ihrem benutzerdefinierten Aktions-Handler erstellen.

Seite mit Handler für E-Mail-Aktionen erstellen

  1. Firebase fügt Ihrer Aktions-Handler-URL mehrere Suchparameter hinzu, wenn generiert Nutzerverwaltungs-E-Mails. Beispiel:

    https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy...&lang=fr

    Diese Parameter geben die Aufgabe der Nutzerverwaltung an, die der Nutzer ausführt. Die Seite mit dem E-Mail-Aktions-Handler muss die folgenden Abfrageparameter verarbeiten:

    Parameter
    Modus

    Die auszuführende Aktion zur Nutzerverwaltung. Folgende Werte sind möglich:

    • resetPassword
    • recoverEmail
    • verifyEmail
    oobCode Ein Einmalcode, der zur Identifizierung und Überprüfung einer Anfrage verwendet wird
    apiKey API-Schlüssel Ihres Firebase-Projekts zur besseren Übersicht
    WeiterURL Dies ist eine optionale URL, die eine Möglichkeit bietet, den Status an die App über eine URL. Das gilt für die Modi „Passwort zurücksetzen“ und „E-Mail-Bestätigung“. Wenn Sie eine E-Mail zur Passwortzurücksetzung oder Bestätigungs-E-Mail, muss ein ActionCodeSettings-Objekt mit einer Fortsetzungs-URL angegeben werden, damit dies verfügbar ist. Dieses Nutzenden können genau da weitermachen, wo sie aufgehört haben. nach einer E-Mail-Aktion.
    lang

    Dies ist das optionale BCP47- Sprach-Tag, das die Sprache des Nutzers angibt (z. B. fr). Mit diesem Wert können Sie Ihren Nutzern lokalisierte Seiten für E-Mail-Aktions-Handler bereitstellen.

    Die Lokalisierung kann über die Firebase Console oder dynamisch festgelegt werden, indem die entsprechende Client-API aufrufen, bevor die E-Mail ausgelöst wird Aktion ausführen. Beispiel in JavaScript: firebase.auth().languageCode = 'fr';.

    Achten Sie darauf, dass die Lokalisierung des E-Mail-Aktions-Handlers mit der der E-Mail-Vorlage übereinstimmt, damit die Nutzeroberfläche einheitlich ist.

    Das folgende Beispiel zeigt, wie Sie die Abfrageparameter in einer browserbasierten Handlers verwendet. Sie können den Handler auch als Node.js-Anwendung mit ähnlicher Logik implementieren.

    WebWeb
    import { initializeApp } from "firebase/app";
    import { getAuth } from "firebase/auth";
    
    document.addEventListener('DOMContentLoaded', () => {
      // TODO: Implement getParameterByName()
    
      // Get the action to complete.
      const mode = getParameterByName('mode');
      // Get the one-time code from the query parameter.
      const actionCode = getParameterByName('oobCode');
      // (Optional) Get the continue URL from the query parameter if available.
      const continueUrl = getParameterByName('continueUrl');
      // (Optional) Get the language code if available.
      const lang = getParameterByName('lang') || 'en';
    
      // Configure the Firebase SDK.
      // This is the minimum configuration required for the API to be used.
      const config = {
        'apiKey': "YOUR_API_KEY" // Copy this key from the web initialization
                                 // snippet found in the Firebase console.
      };
      const app = initializeApp(config);
      const auth = getAuth(app);
    
      // Handle the user management action.
      switch (mode) {
        case 'resetPassword':
          // Display reset password handler and UI.
          handleResetPassword(auth, actionCode, continueUrl, lang);
          break;
        case 'recoverEmail':
          // Display email recovery handler and UI.
          handleRecoverEmail(auth, actionCode, lang);
          break;
        case 'verifyEmail':
          // Display email verification handler and UI.
          handleVerifyEmail(auth, actionCode, continueUrl, lang);
          break;
        default:
          // Error: invalid mode.
      }
    }, false);
    document.addEventListener('DOMContentLoaded', () => {
      // TODO: Implement getParameterByName()
    
      // Get the action to complete.
      var mode = getParameterByName('mode');
      // Get the one-time code from the query parameter.
      var actionCode = getParameterByName('oobCode');
      // (Optional) Get the continue URL from the query parameter if available.
      var continueUrl = getParameterByName('continueUrl');
      // (Optional) Get the language code if available.
      var lang = getParameterByName('lang') || 'en';
    
      // Configure the Firebase SDK.
      // This is the minimum configuration required for the API to be used.
      var config = {
        'apiKey': "YOU_API_KEY" // Copy this key from the web initialization
                                // snippet found in the Firebase console.
      };
      var app = firebase.initializeApp(config);
      var auth = app.auth();
    
      // Handle the user management action.
      switch (mode) {
        case 'resetPassword':
          // Display reset password handler and UI.
          handleResetPassword(auth, actionCode, continueUrl, lang);
          break;
        case 'recoverEmail':
          // Display email recovery handler and UI.
          handleRecoverEmail(auth, actionCode, lang);
          break;
        case 'verifyEmail':
          // Display email verification handler and UI.
          handleVerifyEmail(auth, actionCode, continueUrl, lang);
          break;
        default:
          // Error: invalid mode.
      }
    }, false);
  2. Verarbeite Anfragen zum Zurücksetzen des Passworts, indem du zuerst den Aktionscode bei verifyPasswordResetCode überprüfst. Fordere dann ein neues Passwort vom Nutzer an und leite es an confirmPasswordReset weiter. Beispiel:

    WebWeb
    import { verifyPasswordResetCode, confirmPasswordReset } from "firebase/auth";
    
    function handleResetPassword(auth, actionCode, continueUrl, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
    
      // Verify the password reset code is valid.
      verifyPasswordResetCode(auth, actionCode).then((email) => {
        const accountEmail = email;
    
        // TODO: Show the reset screen with the user's email and ask the user for
        // the new password.
        const newPassword = "...";
    
        // Save the new password.
        confirmPasswordReset(auth, actionCode, newPassword).then((resp) => {
          // Password reset has been confirmed and new password updated.
    
          // TODO: Display a link back to the app, or sign-in the user directly
          // if the page belongs to the same domain as the app:
          // auth.signInWithEmailAndPassword(accountEmail, newPassword);
    
          // TODO: If a continue URL is available, display a button which on
          // click redirects the user back to the app via continueUrl with
          // additional state determined from that URL's parameters.
        }).catch((error) => {
          // Error occurred during confirmation. The code might have expired or the
          // password is too weak.
        });
      }).catch((error) => {
        // Invalid or expired action code. Ask user to try to reset the password
        // again.
      });
    }
    function handleResetPassword(auth, actionCode, continueUrl, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
    
      // Verify the password reset code is valid.
      auth.verifyPasswordResetCode(actionCode).then((email) => {
        var accountEmail = email;
    
        // TODO: Show the reset screen with the user's email and ask the user for
        // the new password.
        var newPassword = "...";
    
        // Save the new password.
        auth.confirmPasswordReset(actionCode, newPassword).then((resp) => {
          // Password reset has been confirmed and new password updated.
    
          // TODO: Display a link back to the app, or sign-in the user directly
          // if the page belongs to the same domain as the app:
          // auth.signInWithEmailAndPassword(accountEmail, newPassword);
    
          // TODO: If a continue URL is available, display a button which on
          // click redirects the user back to the app via continueUrl with
          // additional state determined from that URL's parameters.
        }).catch((error) => {
          // Error occurred during confirmation. The code might have expired or the
          // password is too weak.
        });
      }).catch((error) => {
        // Invalid or expired action code. Ask user to try to reset the password
        // again.
      });
    }
  3. Bei Widerrufen von Änderungen von E-Mail-Adressen muss zuerst der Aktionscode verifiziert werden mit checkActionCode; Stellen Sie dann die E-Mail-Adresse des Nutzers mit applyActionCode. Beispiel:

    WebWeb
    import { checkActionCode, applyActionCode, sendPasswordResetEmail } from "firebase/auth";
    
    function handleRecoverEmail(auth, actionCode, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
      let restoredEmail = null;
      // Confirm the action code is valid.
      checkActionCode(auth, actionCode).then((info) => {
        // Get the restored email address.
        restoredEmail = info['data']['email'];
    
        // Revert to the old email.
        return applyActionCode(auth, actionCode);
      }).then(() => {
        // Account email reverted to restoredEmail
    
        // TODO: Display a confirmation message to the user.
    
        // You might also want to give the user the option to reset their password
        // in case the account was compromised:
        sendPasswordResetEmail(auth, restoredEmail).then(() => {
          // Password reset confirmation sent. Ask user to check their email.
        }).catch((error) => {
          // Error encountered while sending password reset code.
        });
      }).catch((error) => {
        // Invalid code.
      });
    }
    function handleRecoverEmail(auth, actionCode, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
      var restoredEmail = null;
      // Confirm the action code is valid.
      auth.checkActionCode(actionCode).then((info) => {
        // Get the restored email address.
        restoredEmail = info['data']['email'];
    
        // Revert to the old email.
        return auth.applyActionCode(actionCode);
      }).then(() => {
        // Account email reverted to restoredEmail
    
        // TODO: Display a confirmation message to the user.
    
        // You might also want to give the user the option to reset their password
        // in case the account was compromised:
        auth.sendPasswordResetEmail(restoredEmail).then(() => {
          // Password reset confirmation sent. Ask user to check their email.
        }).catch((error) => {
          // Error encountered while sending password reset code.
        });
      }).catch((error) => {
        // Invalid code.
      });
    }
  4. Rufen Sie applyActionCode an, um die Bestätigung der E-Mail-Adresse zu veranlassen. Beispiel:

    WebWeb
    function handleVerifyEmail(auth, actionCode, continueUrl, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
      // Try to apply the email verification code.
      applyActionCode(auth, actionCode).then((resp) => {
        // Email address has been verified.
    
        // TODO: Display a confirmation message to the user.
        // You could also provide the user with a link back to the app.
    
        // TODO: If a continue URL is available, display a button which on
        // click redirects the user back to the app via continueUrl with
        // additional state determined from that URL's parameters.
      }).catch((error) => {
        // Code is invalid or expired. Ask the user to verify their email address
        // again.
      });
    }
    function handleVerifyEmail(auth, actionCode, continueUrl, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
      // Try to apply the email verification code.
      auth.applyActionCode(actionCode).then((resp) => {
        // Email address has been verified.
    
        // TODO: Display a confirmation message to the user.
        // You could also provide the user with a link back to the app.
    
        // TODO: If a continue URL is available, display a button which on
        // click redirects the user back to the app via continueUrl with
        // additional state determined from that URL's parameters.
      }).catch((error) => {
        // Code is invalid or expired. Ask the user to verify their email address
        // again.
      });
    }
  5. Hosten Sie die Seite irgendwo, z. B. unter Firebase Hosting.

Als Nächstes müssen Sie Ihr Firebase-Projekt so konfigurieren, dass es mit Ihrer benutzerdefinierten E-Mail-Adresse verknüpft ist Aktions-Handler in seinen E-Mails zur Nutzerverwaltung.

So konfigurieren Sie Ihr Firebase-Projekt für die Verwendung Ihres benutzerdefinierten E-Mail-Aktions-Handlers:

  1. Öffnen Sie Ihr Projekt in der Firebase Console.
  2. Rufen Sie im Bereich Authentifizierung die Seite E-Mail-Vorlagen auf.
  3. Klicken Sie in einem der E-Mail-Typen auf das Stiftsymbol, um die E-Mail-Vorlage.
  4. Klicken Sie auf Aktions-URL anpassen und geben Sie die URL Ihres benutzerdefinierten E-Mail-Aktionshandlers an.

Nachdem Sie die URL gespeichert haben, wird sie von allen E-Mail-Vorlagen Ihres Firebase-Projekts verwendet.