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 odsyłają do domyślnego modułu obsługi działań, czyli strony internetowej hostowanej pod adresem URL w domenie Hostingu Firebase Twojego projektu.
Możesz zamiast tego utworzyć i hostować niestandardowy moduł działania e-maila, aby przeprowadzić niestandardowe przetwarzanie i zintegrować go z witryną.
Aby wykonać te czynności związane z zarządzaniem użytkownikami, użytkownik musi użyć modułu obsługi działania e-maila:
- 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, aby mogli cofnąć zmianę.
- Weryfikowanie adresów e-mail
Aby dostosować element obsługi działania e-maila w projekcie Firebase, musisz utworzyć i hostować stronę internetową, która korzysta z pakietu SDK JavaScript Firebase do sprawdzania ważności żądania i jego realizacji. Następnie musisz dostosować szablony e-maili w projekcie Firebase, aby połączyć je z obsługą niestandardowego działania.
Tworzenie strony funkcji obsługi działania e-maila
Gdy Firebase generuje e-maile dotyczące zarządzania użytkownikami, dodaje do adresu URL modułu obsługi działania kilka parametrów zapytania. 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 użytkownik wykonuje. Strona przetwarzająca działanie dotyczące e-maila musi obsługiwać te parametry zapytania:
Parametry tryb Do wykonania działanie związane z zarządzaniem użytkownikami. Może mieć jedną z tych wartości:
resetPassword
recoverEmail
verifyEmail
oobCode jednorazowy kod służący do identyfikacji i weryfikacji prośby; apiKey Klucz interfejsu API Twojego projektu Firebase (podany dla Twojej wygody) continueUrl 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 weryfikacji adresu e-mail. Podczas wysyłania e-maila z resetem hasła lub e-maila weryfikacyjnego należy określić obiekt ActionCodeSettings
z adresem URL kontynuacji, aby był on dostępny. Dzięki temu użytkownik może kontynuować od miejsca, w którym zakończył, po wykonaniu działania w e-mailu.lang To opcjonalny tag języka BCP47 reprezentujący lokalizację użytkownika (np.
fr
). Możesz użyć tej wartości, aby wyświetlać użytkownikom zlokalizowane strony przetwarzania działań e-mail.Lokalizację można ustawić w konsoli Firebase lub dynamicznie, wywołując odpowiedni interfejs API klienta przed wywołaniem działania wysyłania e-maila. Na przykład za pomocą JavaScripta:
firebase.auth().languageCode = 'fr';
Aby zapewnić użytkownikom spójne wrażenia, upewnij się, że lokalizacja funkcji obsługi działania e-maila jest zgodna z lokalizacją szablonu e-maila.
Poniższy przykład pokazuje, jak można obsługiwać parametry zapytania w obsługniku opartym na przeglądarce. (możesz też zaimplementować tego modułu za pomocą aplikacji 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);
Obsługuj prośby o zresetowanie hasła, najpierw weryfikując kod działania za pomocą funkcji
verifyPasswordResetCode
, a potem pobierając nowe hasło od użytkownika i przekazując je do funkcjiconfirmPasswordReset
. 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. }); }
Aby anulować zmianę adresu e-mail, najpierw za pomocą
checkActionCode
potwierdź kod działania, a następnie przywróć adres e-mail użytkownika za pomocąapplyActionCode
. 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. }); }
Aby przeprowadzić weryfikację adresu e-mail, zadzwoń pod numer
applyActionCode
. Przykład:Web
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. }); }
Web
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ść stronę gdzieś na serwerze, np. na Firebase Hosting.
Następnie musisz skonfigurować projekt Firebase, aby połączyć go z niestandardowym modułem obsługi działania e-maila w e-mailach dotyczących zarządzania użytkownikami.
Linkowanie do niestandardowego modułu obsługi w szablonach e-maili
Aby skonfigurować projekt Firebase tak, aby korzystał z niestandardowego modułu obsługi działania e-mail:
- Otwórz projekt w konsoli Firebase.
- W sekcji Autoryzacja otwórz stronę Szablony e-maili.
- Aby edytować szablon e-maila, kliknij ikonę ołówka przy dowolnym z elementów w sekcji Typy e-maili.
- Kliknij Dostosuj adres URL działania i podaj adres URL niestandardowego modułu obsługi działania e-maila.
Po zapisaniu adresu URL będzie on używany przez wszystkie szablony e-maili w Twoim projekcie Firebase.