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 do niego e-maili. 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 zawierają link do domyślnego modułu obsługi działań, czyli strony internetowej hostowanej pod adresem URL w domenie Hostingu Firebase projektu.
Możesz też utworzyć i hostować niestandardowy moduł obsługi działań e-mailowych, aby przeprowadzać niestandardowe przetwarzanie i zintegrować go ze swoją witryną.
W przypadku tych działań związanych z zarządzaniem użytkownikami użytkownik musi wykonać działanie za pomocą modułu obsługi działań e-mailowych:
- Resetowanie haseł
- Cofanie zmian adresu e-mail – gdy użytkownicy zmieniają podstawowy adres e-mail swoich kont, Firebase wysyła e-maila na ich stary adres, co umożliwia im cofnięcie zmiany.
- Potwierdzanie adresów e-mail
Aby dostosować moduł obsługi działań e-mailowych projektu w Firebase, musisz utworzyć i hostować stronę internetową, która używa pakietu Firebase JavaScript SDK do weryfikowania ważności żądania i jego realizacji. Następnie musisz dostosować szablony e-maili projektu Firebase, aby zawierały link do niestandardowego modułu obsługi działań.
Tworzenie strony modułu obsługi działań e-mailowych
Gdy Firebase generuje e-maile dotyczące zarządzania użytkownikami, dodaje do adresu URL modułu obsługi działań kilka parametrów zapytania. 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 modułu obsługi działań e-mailowych musi obsługiwać te parametry zapytania:
Parametry tryb Działanie związane z zarządzaniem użytkownikami, które ma zostać wykonane. Może przyjmować jedną z tych wartości:
resetPasswordrecoverEmailverifyEmail
oobCode Jednorazowy kod służący do identyfikacji i weryfikacji żądania. apiKey Klucz API projektu Firebase, podany dla wygody. continueUrl Opcjonalny adres URL, który umożliwia przekazywanie stanu z powrotem do aplikacji za pomocą adresu URL. Jest to istotne w przypadku trybów resetowania hasła i weryfikacji adresu e-mail. Aby ta opcja była dostępna, podczas wysyłania e-maila z prośbą o zresetowanie hasła lub e-maila weryfikacyjnego należy określić obiekt ActionCodeSettingsz adresem URL dalszego działania. Dzięki temu użytkownik może kontynuować działanie po wykonaniu działania e-mailowego.język Opcjonalny tag języka BCP47 reprezentujący ustawienia regionalne użytkownika (np.
fr). Możesz użyć tej wartości, aby udostępnić użytkownikom zlokalizowane strony modułu obsługi działań e-mailowych.Lokalizację można ustawić w konsoli Firebase lub dynamicznie, wywołując odpowiedni interfejs API klienta przed wywołaniem działania e-mailowego. Na przykład w JavaScript:
firebase.auth().languageCode = 'fr';.Aby zapewnić spójność obsługi, upewnij się, że lokalizacja modułu obsługi działań e-mailowych jest zgodna z lokalizacją szablonu e-maila.
W tym przykładzie pokazujemy, jak można obsługiwać parametry zapytania w module obsługi opartym na przeglądarce. (Moduł obsługi możesz też zaimplementować jako aplikację 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 żądania resetowania hasła, najpierw weryfikując kod działania za pomocą funkcji
verifyPasswordResetCode, a następnie 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. }); }
Obsługuj cofnięcia zmian adresu e-mail, najpierw weryfikując kod działania za pomocą funkcji
checkActionCode, a następnie przywracając adres e-mail użytkownika za pomocą funkcjiapplyActionCode. 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. }); }
Obsługuj weryfikację adresu e-mail, wywołując funkcję
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. }); }
Hostuj stronę w dowolnym miejscu, np. w Firebase Hosting.
Następnie musisz skonfigurować projekt w Firebase tak, aby w e-mailach dotyczących zarządzania użytkownikami zawierał link do niestandardowego modułu obsługi działań e-mailowych.
Dodawanie linku do niestandardowego modułu obsługi w szablonach e-maili
Aby skonfigurować projekt w Firebase tak, aby używał niestandardowego modułu obsługi działań e-mailowych:
W konsoli Firebase otwórz kartę Zabezpieczenia > Uwierzytelnianie > Szablony.
W dowolnym wpisie Typy e-maili kliknij ikonę ołówka, aby edytować szablon e-maila.
Kliknij Dostosuj adres URL działania i podaj adres URL niestandardowego modułu obsługi działań e-mailowych.
Po zapisaniu adresu URL będzie on używany przez wszystkie szablony e-maili projektu Firebase.