Niektóre działania związane z zarządzaniem użytkownikami, takie jak aktualizacja adresu e-mail użytkownika i resetowanie hasła użytkownika, skutkują wysłaniem wiadomości e-mail do użytkownika. Te wiadomości e-mail zawierają łącza, które odbiorcy mogą otworzyć, aby zakończyć lub anulować czynność zarządzania użytkownikami. Domyślnie e-maile dotyczące zarządzania użytkownikami prowadzą do domyślnego modułu obsługi akcji, czyli strony internetowej hostowanej pod adresem URL w domenie Hostingu Firebase Twojego projektu.
Zamiast tego możesz utworzyć i hostować niestandardową procedurę obsługi wiadomości e-mail, aby wykonać niestandardowe przetwarzanie i zintegrować procedurę obsługi wiadomości e-mail z witryną internetową.
Następujące działania związane z zarządzaniem użytkownikami wymagają od użytkownika wykonania działania przy użyciu programu 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 umożliwia im cofnięcie zmiany
- Weryfikacja adresów e-mail
Aby dostosować moduł obsługi działań e-mail w projekcie Firebase, musisz utworzyć i hostować stronę internetową, która korzysta z Firebase JavaScript SDK, aby zweryfikować poprawność żądania i zrealizować żądanie. Następnie musisz dostosować szablony wiadomości e-mail projektu Firebase, aby połączyć je z modułem obsługi działań niestandardowych.
Utwórz stronę obsługi akcji e-mail
Firebase dodaje kilka parametrów zapytania do adresu URL modułu obsługi akcji podczas generowania wiadomości e-mail dotyczących 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 użytkownik wykonuje. Twoja strona obsługi działań e-mail musi obsługiwać następujące parametry zapytania:
Parametry tryb Czynność zarządzania użytkownikami do wykonania. Może być jedną z następujących wartości:
-
resetPassword
-
recoverEmail
-
verifyEmail
oobKod Jednorazowy kod służący do identyfikacji i weryfikacji żądania Klucz API Klucz API Twojego projektu Firebase, podany dla wygody kontynuujUrl Jest to opcjonalny adres URL, który zapewnia sposób przekazywania stanu z powrotem do aplikacji za pośrednictwem adresu URL. Dotyczy to trybów resetowania hasła i weryfikacji adresu e-mail. Podczas wysyłania wiadomości e-mail dotyczącej resetowania hasła lub wiadomości weryfikacyjnej 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 przerwał po akcji e-mail.lang Jest to opcjonalny znacznik języka BCP47 reprezentujący ustawienia regionalne użytkownika (na przykład
fr
). Możesz użyć tej wartości, aby udostępnić użytkownikom zlokalizowane strony obsługi akcji e-mail.Lokalizację można ustawić za pomocą konsoli Firebase lub dynamicznie, wywołując odpowiedni interfejs API klienta przed uruchomieniem akcji e-mail. Na przykład za pomocą JavaScript:
firebase.auth().languageCode = 'fr';
.Aby zapewnić spójne wrażenia użytkownika, upewnij się, że lokalizacja modułu obsługi akcji e-mail jest zgodna z szablonem wiadomości e-mail.
Poniższy przykład pokazuje, jak można obsłużyć parametry zapytania w programie obsługi opartym na przeglądarce. (Można również zaimplementować procedurę obsługi jako aplikację Node.js przy użyciu 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': "YOU_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 namespaced API
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 żądania resetowania hasła, najpierw weryfikując kod akcji za pomocą
verifyPasswordResetCode
; następnie uzyskaj nowe hasło od użytkownika i przekaż je doconfirmPasswordReset
. Na 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. }); }
Web namespaced API
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. }); }
Obsługuj odwołania zmiany adresu e-mail, najpierw weryfikując kod akcji za pomocą
checkActionCode
; następnie przywróć adres e-mail użytkownika za pomocąapplyActionCode
. Na 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. }); }
Web namespaced API
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. }); }
Obsługuj weryfikację adresu e-mail, wywołując
applyActionCode
. Na 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. }); }
Web namespaced 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. 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. }); }
Hostuj gdzieś stronę, na przykład użyj Hostingu Firebase .
Następnie musisz skonfigurować swój projekt Firebase, aby w wiadomościach e-mail dotyczących zarządzania użytkownikami łączył się z niestandardową procedurą obsługi e-maili.
Połącz się z niestandardowym modułem obsługi w szablonach wiadomości e-mail
Aby skonfigurować projekt Firebase do korzystania z niestandardowego modułu obsługi e-maili:
- Otwórz swój projekt w konsoli Firebase .
- Przejdź do strony Szablony wiadomości e-mail w sekcji Uwierzytelnianie .
- W dowolnym wpisie Typy wiadomości e-mail kliknij ikonę ołówka, aby edytować szablon wiadomości e-mail.
- Kliknij opcję Dostosuj adres URL akcji i podaj adres URL niestandardowej procedury obsługi e-maili.
Po zapisaniu adresu URL będzie on używany przez wszystkie szablony e-maili Twojego projektu Firebase.