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 lub resetowanie hasła użytkownika, powoduje wysłanie do niego wiadomości e-mail. Te e-maile zawierają linki, które odbiorcy mogą otworzyć, aby dokończyć lub anulować użytkownika. zarządzania. Domyślnie e-maile dotyczące zarządzania użytkownikami zawierają link do działania domyślnego to strona internetowa hostowana pod adresem URL w Hostingu Firebase Twojego projektu w Twojej domenie.

Zamiast tego możesz utworzyć i hostować niestandardowy moduł obsługi działań w e-mailach i zintegrować moduł obsługi działań w e-mailach ze swoją 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ń dotyczących poczty e-mail:

  • Resetuję hasła
  • cofnięcie zmian adresu e-mail, gdy użytkownik zmieni swoje konto. główny adresy e-mail, Firebase wysyła e-maile na stare adresy, które pozwalają na aby cofnąć zmianę
  • Weryfikuję adresy e-mail

Aby dostosować moduł obsługi działań e-mail w projekcie Firebase, musisz utworzyć hostować stronę internetową, która korzysta z pakietu SDK Firebase JavaScript do weryfikowania żądania jest prawidłowe i wypełnić żądanie. Następnie musisz dostosować Firebase szablonów e-maili projektu, które można połączyć z niestandardowym modułem obsługi działań.

Tworzenie strony modułu obsługi działań e-mail

  1. Firebase dodaje kilka parametrów zapytania do adresu URL modułu obsługi działań, generuje e-maile do 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 należy wykonać dokończenie. Strona modułu obsługi działań e-mail musi obsługiwać to zapytanie parametry:

    Parametry
    tryb

    Działanie związane z zarządzaniem użytkownikami, które ma zostać wykonane. Może być jednym z następujące wartości:

    • resetPassword
    • recoverEmail
    • verifyEmail
    Kod OobCode Jednorazowy kod używany do identyfikowania i weryfikacji żądania
    klucz apiKey Klucz interfejsu API Twojego projektu Firebase (dla wygody)
    ContinueUrl Jest to opcjonalny URL, który umożliwia przekazanie stanu z powrotem do z aplikacji za pomocą adresu URL. Dotyczy to resetowania hasła i wysyłania e-maili trybami weryfikacji. Podczas wysyłania wiadomości e-mail do zresetowania hasła lub e-maila weryfikacyjnego, obiekt ActionCodeSettings wymaga określony za pomocą adresu URL kontynuacji, aby był dostępny. Ten umożliwia użytkownikowi kontynuowanie od tego samego miejsca po działaniu e-maila.
    lang

    Jest to opcjonalne BCP47 . tag języka reprezentujący region użytkownika (np. fr). Możesz użyć tej wartości, by udostępnić zlokalizowane e-maile stron modułu obsługi działań.

    Lokalizacja można ustawić w konsoli Firebase lub dynamicznie przez wywołanie odpowiedniego interfejsu API klienta przed aktywacją e-maila. działania. Na przykład za pomocą JavaScriptu: firebase.auth().languageCode = 'fr';

    Aby zapewnić użytkownikom spójne wrażenia, upewnij się, że moduł obsługi działań e-mail język jest zgodny z szablonem e-maila.

    Z przykładu poniżej dowiesz się, jak obsługiwać parametry zapytania w tagu dla obsługi opartej na przeglądarce. Możesz również zaimplementować moduł obsługi jako środowisko Node.js w podobny sposób).

    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. Aby obsługiwać prośby o zresetowanie hasła, najpierw zweryfikuj kod działania za pomocą verifyPasswordResetCode; a następnie uzyskaj nowe hasło od użytkownika i je przekaż do: confirmPasswordReset. Przykład:

    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. Aby obsługiwać odwołania zmiany adresu e-mail, najpierw weryfikuj kod działania checkActionCode; a następnie przywróć jego adres e-mail applyActionCode Przykład:

    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. Zweryfikuj adres e-mail, dzwoniąc pod numer applyActionCode. Przykład:

    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. Umieść stronę gdzieś, na przykład przy użyciu Firebase Hosting.

Następnie musisz skonfigurować projekt Firebase, aby połączyć go z Twoim niestandardowym adresem e-mail modułu obsługi działań w e-mailach do zarządzania użytkownikami.

Aby skonfigurować projekt Firebase pod kątem korzystania z niestandardowego modułu obsługi działań w e-mailach:

  1. Otwórz projekt w konsoli Firebase.
  2. Otwórz stronę Szablony e-maili w sekcji Uwierzytelnianie.
  3. W dowolnym z wpisów Typy e-maili kliknij ikonę ołówka, aby edytować szablon e-maila.
  4. Kliknij Dostosuj URL działania i podaj adres URL niestandardowego e-maila. modułu obsługi działań.

Po zapisaniu adresu URL będzie on używany przez całą pocztę e-mail projektu Firebase szablonów.