Tworzenie niestandardowych modułów obsługi działań e-mail

Niektóre działania związane z zarządzaniem użytkownikami, takie jak aktualizowanie adresu e-mail użytkownika i resetowanie jego hasła, powodują wysyłanie e-maili do użytkownika. Te e-maile zawierają linki, które odbiorcy mogą otworzyć, aby dokończyć lub anulować działanie związane z zarządzaniem użytkownikami. Domyślnie e-maile dotyczące zarządzania użytkownikami zawierają link do domyślnego modułu obsługi działań, czyli strony internetowej hostowanej pod adresem URL w domenie hostingu Firebase projektu.

Zamiast tego możesz utworzyć i hostować niestandardowy moduł obsługi działań związanych z pocztą e-mail, aby wykonywać niestandardowe przetwarzanie i zintegrować moduł obsługi działań związanych z pocztą e-mail z witryną.

Te działania związane z zarządzaniem użytkownikami wymagają od użytkownika wykonania działania za pomocą modułu obsługi działań e-mail:

  • Resetowanie haseł
  • Anulowanie zmian adresu e-mail – gdy użytkownicy zmieniają podstawowe adresy e-mail swoich kont, Firebase wysyła e-maila na ich stare adresy, co pozwala im cofnąć zmianę.
  • Weryfikowanie adresów e-mail

Aby dostosować moduł obsługi działań związanych z e-mailami w projekcie w Firebase, musisz utworzyć i hostować stronę internetową, która używa pakietu Firebase JavaScript SDK do weryfikacji ważności żądania i jego realizacji. Następnie musisz dostosować szablony e-maili projektu Firebase, aby połączyć je z niestandardowym modułem obsługi działań.

Tworzenie strony modułu obsługi działań związanych z e-mailami

  1. Firebase dodaje kilka parametrów zapytania do adresu URL modułu obsługi działań, gdy generuje e-maile dotyczące zarządzania użytkownikami. Na przykład:

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

    Te parametry określają zadanie zarządzania użytkownikami, które wykonuje użytkownik. Strona modułu obsługi działań związanych z e-mailami musi obsługiwać te parametry zapytania:

    Parametry
    tryb

    Działanie związane z zarządzaniem użytkownikami, które ma zostać wykonane. Może to być jedna z tych wartości:

    • resetPassword
    • recoverEmail
    • verifyEmail
    oobCode Jednorazowy kod służący do identyfikacji i weryfikacji żądania
    apiKey Klucz interfejsu API projektu w Firebase, podany dla wygody
    continueUrl Jest to opcjonalny adres URL, który umożliwia przekazywanie stanu z powrotem do aplikacji za pomocą adresu URL. Dotyczy to trybów resetowania hasła i potwierdzania adresu e-mail. Podczas wysyłania e-maila z prośbą o resetowanie hasła lub e-maila weryfikacyjnego należy określić obiekt ActionCodeSettings z URL-em dalszego działania, aby ta opcja była dostępna. Dzięki temu użytkownik może kontynuować od miejsca, w którym przerwał, po wykonaniu działania w e-mailu.
    lang

    Jest to opcjonalny tag języka BCP47 reprezentujący ustawienia regionalne użytkownika (np. fr). Możesz użyć tej wartości, aby udostępnić użytkownikom zlokalizowane strony modułu obsługi działań w e-mailach.

    Lokalizację można ustawić w konsoli Firebase lub dynamicznie, wywołując odpowiedni interfejs API klienta przed aktywacją działania związanego z e-mailem. Na przykład za pomocą JavaScriptu:firebase.auth().languageCode = 'fr';.

    Aby zapewnić spójne wrażenia użytkownika, upewnij się, że lokalizacja modułu obsługi działań w e-mailu jest zgodna z lokalizacją szablonu e-maila.

    Poniższy przykład pokazuje, jak możesz obsługiwać parametry zapytania w module obsługi opartym na przeglądarce. (Możesz też zaimplementować moduł obsługi jako aplikację Node.js, używając podobnej logiki).

    Web

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

    Web

    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. Obsługuj żądania resetowania hasła, najpierw weryfikując kod działania za pomocą verifyPasswordResetCode, a następnie pobierając nowe hasło od użytkownika i przekazując je do confirmPasswordReset. Na przykład:

    Web

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

    Web

    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. Obsługuj anulowanie zmiany adresu e-mail, najpierw weryfikując kod działania za pomocą checkActionCode, a następnie przywracając adres e-mail użytkownika za pomocą applyActionCode. Na przykład:

    Web

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

    Web

    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. Obsługuj weryfikację adresu e-mail, wyświetlając przycisk potwierdzenia i wymagając kliknięcia przez użytkownika przed wywołaniem metody applyActionCode. Wymaganie kliknięcia przez użytkownika uniemożliwia automatycznym skanerom zabezpieczeń poczty e-mail, które pobierają linki z wyprzedzeniem, wykorzystanie jednorazowych kodów weryfikacyjnych, zanim użytkownik otworzy stronę:

    Web

    import { applyActionCode } from "firebase/auth";
    
    function handleVerifyEmail(auth, actionCode, continueUrl, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
      // Show the confirmation button and apply the action code only after
      // the user clicks it.
      const confirmButton = document.getElementById('confirm-verify-email');
      if (!confirmButton) {
        return;
      }
      confirmButton.hidden = false;
      confirmButton.addEventListener('click', () => {
        confirmButton.disabled = true;
        applyActionCode(auth, actionCode).then(() => {
          // Email address has been verified. Display a confirmation
          // message, and if continueUrl is available, provide a button
          // that redirects back to the app.
        }).catch((error) => {
          confirmButton.disabled = false;
          // Code is invalid, expired, or failed due to a network error.
          // Ask the user to verify their email address again if needed.
        });
      });
    }
    

    Web

    function handleVerifyEmail(auth, actionCode, continueUrl, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
      // Show the confirmation button and apply the action code only after
      // the user clicks it.
      var confirmButton = document.getElementById('confirm-verify-email');
      if (!confirmButton) {
        return;
      }
      confirmButton.hidden = false;
      confirmButton.addEventListener('click', function() {
        confirmButton.disabled = true;
        auth.applyActionCode(actionCode).then(function() {
          // Email address has been verified. Display a confirmation
          // message, and if continueUrl is available, provide a button
          // that redirects back to the app.
        }).catch(function(error) {
          confirmButton.disabled = false;
          // Code is invalid, expired, or failed due to a network error.
          // Ask the user to verify their email address again if needed.
        });
      });
    }
    
  5. Umieść stronę na serwerze, np. Firebase Hosting.

Backend Uwierzytelniania Firebase zarządza kluczem interfejsu API umieszczonym w wygenerowanych linkach do działań, np. parametrem apiKey w adresie URL. Jeśli zmienisz klucze interfejsu API projektu lub usuniesz klucz, który był pierwotnie powiązany z Firebase Auth, użytkownicy mogą otrzymać linki z nieprawidłowymi kluczami, co spowoduje błędy auth/invalid-api-key.

Aby rozwiązać ten problem:

  • Jeśli używasz Hostingu Firebase: klucz interfejsu API może być przechowywany w pamięci podręcznej w init.json. Wdróż nową wersję witryny Hosting (firebase deploy --only hosting), aby wymusić na usłudze metadanych backendu ponowne wygenerowanie konfiguracji z aktywnym kluczem interfejsu API.
  • Jeśli trzeba zaktualizować sam klucz backendu: ponieważ mapowania klucza interfejsu API backendu nie można zmodyfikować bezpośrednio za pomocą konsoli ani pakietów SDK, musisz skontaktować się z zespołem pomocy, aby poprosić o aktualizację konfiguracji uwierzytelniania backendu w projekcie.

Następnie musisz skonfigurować projekt w Firebase, aby połączyć go z niestandardowym modułem obsługi działań związanych z e-mailami w e-mailach dotyczących zarządzania użytkownikami.

Aby skonfigurować projekt w Firebase tak, aby używał niestandardowego modułu obsługi działań związanych z e-mailami:

  1. W konsoli Firebase otwórz kartę Zabezpieczenia > Uwierzytelnianie > Szablony.

  2. W dowolnym wpisie Typy e-maili kliknij ikonę ołówka, aby edytować szablon e-maila.

  3. Kliknij URL działania niestandardowego i podaj adres URL niestandardowego modułu obsługi działań związanych z e-mailami.

Po zapisaniu adresu URL będzie on używany we wszystkich szablonach e-maili w projekcie w Firebase.