Niektóre działania związane z zarządzaniem użytkownikami, takie jak aktualizowanie adresu e-mail lub resetowanie hasła użytkownika, powodują wysyłanie do niego e-maili. Zawierają one linki, które odbiorcy mogą otworzyć, aby dokończyć lub anulować działanie zarządzania 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 Twojego projektu.
Zamiast tego możesz utworzyć i hostować niestandardowy moduł obsługi działań związanych z pocztą e-mail na potrzeby niestandardowego przetwarzania danych i integracji tego modułu ze swoją witryną.
Te działania związane z zarządzaniem użytkownikami wymagają od użytkownika wykonania tych czynności przy użyciu modułu obsługi działań związanych z e-mailami:
- Resetuję hasła
- cofając zmiany adresów e-mail – gdy użytkownik zmieni podstawowy adres e-mail konta, Firebase wysyła na stare adresy e-maile, aby umożliwić im cofnięcie tej zmiany.
- Weryfikuję adresy e-mail
Aby dostosować moduł obsługi działań związanych z pocztą e-mail w projekcie Firebase, musisz utworzyć i hostować stronę internetową, która korzysta z pakietu Firebase JavaScript SDK do weryfikowania poprawności żądania i jego realizacji. Następnie musisz dostosować szablony e-mail projektu Firebase, by połączyć je z niestandardowym modułem obsługi działań.
Tworzenie strony modułu obsługi działań e-mail
Firebase dodaje kilka parametrów zapytania do adresu URL modułu obsługi działań podczas generowania e-maili do zarządzania użytkownikami. Przykład:
https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy...&lang=fr
Te parametry określają zadanie związane z zarządzaniem użytkownikami, które wykonuje użytkownik. Strona modułu obsługi działań e-mail musi obsługiwać te parametry zapytania:
Parametry tryb Działanie związane z zarządzaniem użytkownikami, które ma zostać wykonane. Może mieć jedną z tych 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 aplikacji za pomocą adresu URL. Dotyczy to trybów resetowania hasła i weryfikacji adresu e-mail. Gdy wysyłasz e-maila do resetowania hasła lub e-maila weryfikacyjnego, obiekt ActionCodeSettings
musi być określony za pomocą adresu URL kontynuacji, aby ten obiekt był dostępny. Dzięki temu użytkownik może kontynuować korzystanie z e-maila od tego samego miejsca, w którym go przerwał.lang To opcjonalny tag języka BCP47 reprezentujący region użytkownika (np.
fr
). Za pomocą tej wartości możesz udostępnić użytkownikom zlokalizowane strony obsługi działań związanych z pocztą e-mail.Lokalizacja można ustawić za pomocą konsoli Firebase lub dynamicznie przez wywołanie odpowiedniego interfejsu API klienta przed uruchomieniem działania dotyczącego e-maila. np. za pomocą JavaScriptu:
firebase.auth().languageCode = 'fr';
.Aby zapewnić spójność informacji, sprawdź, czy lokalizacja modułu obsługi działań e-mail jest zgodna z szablonem e-maila.
Z przykładu poniżej dowiesz się, jak możesz obsłużyć parametry zapytania w module obsługi opartym na przeglądarce. Moduł obsługi możesz też zaimplementować jako aplikację Node.js z użyciem podobnej logiki.
Web Modular API
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);
Interfejs API internetowej przestrzeni nazw
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);
Aby obsługiwać prośby o zresetowanie hasła, najpierw zweryfikuj kod działania za pomocą
verifyPasswordResetCode
. Następnie uzyskaj nowe hasło od użytkownika i przekaż je do usługiconfirmPasswordReset
. Przykład:Web Modular API
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. }); }
Interfejs API internetowej przestrzeni nazw
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. }); }
Odwołaniami zmiany adresu e-mail możesz zarządzać, najpierw weryfikując kod działania w usłudze
checkActionCode
, a następnie przywróć adres e-mail użytkownika za pomocąapplyActionCode
. Przykład:Web Modular API
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. }); }
Interfejs API internetowej przestrzeni nazw
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. }); }
Zweryfikuj adres e-mail, dzwoniąc pod numer
applyActionCode
. Przykład:Web Modular API
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. }); }
Interfejs API internetowej przestrzeni nazw
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. }); }
Umieść gdzieś stronę, np. Hosting Firebase.
Następnie musisz skonfigurować w projekcie Firebase połączenie z niestandardowym modułem obsługi e-maili w e-mailach do zarządzania użytkownikami.
Dodawanie w szablonach e-maili linku do niestandardowego modułu obsługi
Aby skonfigurować projekt Firebase pod kątem korzystania z niestandardowego modułu obsługi działań w e-mailach:
- Otwórz projekt w konsoli Firebase.
- Otwórz stronę Szablony e-maili w sekcji Uwierzytelnianie.
- W sekcji Typy e-maili kliknij ikonę ołówka, aby edytować szablon e-maila.
- Kliknij Dostosuj URL działania i podaj adres URL niestandardowego modułu obsługi e-maili.
Po zapisaniu adresu URL będzie on używany we wszystkich szablonach e-maili w projekcie Firebase.