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, powodują wysyłanie wiadomości e-mail do użytkownika. Te e-maile zawierają łącza, które odbiorcy mogą otworzyć, aby zakończyć lub anulować czynność zarządzania użytkownikami. Domyślnie wiadomości e-mail służące do zarządzania użytkownikami prowadzą do domyślnej procedury obsługi akcji, czyli strony internetowej hostowanej pod adresem URL w domenie Firebase Hosting Twojego projektu.
Zamiast tego możesz utworzyć i hostować niestandardową procedurę obsługi akcji e-mail, aby wykonać niestandardowe przetwarzanie i zintegrować procedurę obsługi akcji e-mail ze swoją witryną internetową.
Następujące akcje związane z zarządzaniem użytkownikami wymagają od użytkownika wykonania akcji przy użyciu procedury obsługi akcji e-mail:
- Resetowanie haseł
- Odwoływanie zmian w adresach e-mail — gdy użytkownicy zmienią podstawowe adresy e-mail na swoich kontach, Firebase wysyła wiadomość e-mail na ich stare adresy, która umożliwia im cofnięcie zmiany
- Weryfikacja adresów e-mail
Aby dostosować procedurę obsługi akcji e-mail w projekcie Firebase, musisz utworzyć i hostować stronę internetową korzystającą z pakietu SDK JavaScript Firebase w celu sprawdzenia ważności żądania i jego realizacji. Następnie musisz dostosować szablony e-maili swojego projektu Firebase, aby zawierały linki do niestandardowej procedury obsługi akcji.
Utwórz stronę obsługi akcji e-mail
Firebase dodaje kilka parametrów zapytania do adresu URL modułu obsługi akcji, gdy generuje wiadomości e-mail służące 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 wykonuje użytkownik. Strona obsługi akcji e-mailowych musi obsługiwać następujące parametry zapytania:
Parametry tryb Akcja zarządzania użytkownikami do zakończenia. Może mieć jedną z następujących wartości:
-
resetPassword
-
recoverEmail
-
verifyEmail
oobCode Kod jednorazowy, służący do identyfikacji i weryfikacji żądania Klucz API Klucz API Twojego projektu Firebase, udostępniony dla wygody kontynuujUrl Jest to opcjonalny adres URL, który umożliwia przekazanie 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 obiekt był dostępny. Dzięki temu użytkownik może kontynuować od miejsca, w którym przerwał po wykonaniu czynności e-mailowej.język 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, używając JavaScript:
firebase.auth().languageCode = 'fr';
.Aby zapewnić spójne doświadczenie użytkownika, upewnij się, że lokalizacja modułu obsługi akcji e-mail jest zgodna z lokalizacją szablonu wiadomości e-mail.
Poniższy przykład pokazuje, jak można obsługiwać parametry zapytania w programie obsługi opartym na przeglądarce. (Możesz także zaimplementować procedurę obsługi jako aplikację Node.js, stosując podobną logikę.)
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);
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 w celuconfirmPasswordReset
. 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. }); }
Zajmij się 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 tak, aby zawierał łącze do niestandardowej procedury obsługi akcji e-mail w wiadomościach e-mail służących do zarządzania użytkownikami.
Link do niestandardowego modułu obsługi w szablonach wiadomości e-mail
Aby skonfigurować projekt Firebase do korzystania z niestandardowej procedury obsługi akcji e-mail:
- Otwórz swój projekt w konsoli Firebase .
- Przejdź do strony Szablony e-maili 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 akcji e-mail.
Po zapisaniu adresu URL będzie on używany we wszystkich szablonach wiadomości e-mail w Twoim projekcie Firebase.