Некоторые действия по управлению пользователями, такие как обновление адреса электронной почты пользователя и сброс пароля, приводят к отправке пользователю электронных писем. Эти письма содержат ссылки, которые получатели могут открыть, чтобы завершить или отменить действие по управлению пользователем. По умолчанию электронные письма по управлению пользователями содержат ссылку на обработчик действий по умолчанию, которым является веб-страница, размещенная по URL-адресу в домене Firebase Hosting вашего проекта.
Вместо этого вы можете создать и разместить собственный обработчик действий с электронной почтой для выполнения пользовательской обработки и интеграции обработчика действий с электронной почтой с вашим веб-сайтом.
Для выполнения следующих действий по управлению пользователями необходимо использовать обработчик событий электронной почты:
- Сброс паролей
- Отмена изменений адреса электронной почты — когда пользователи меняют основной адрес электронной почты в своих учетных записях, Firebase отправляет электронное письмо на их старые адреса, позволяющее отменить изменение.
- Проверка адресов электронной почты
Чтобы настроить обработчик событий отправки электронных писем в вашем проекте Firebase, необходимо создать и разместить веб-страницу, которая использует JavaScript SDK Firebase для проверки корректности запроса и его выполнения. Затем необходимо настроить шаблоны электронных писем вашего проекта Firebase, чтобы они содержали ссылки на ваш пользовательский обработчик событий.
Создайте страницу обработчика действий электронной почты.
При генерации писем для управления пользователями Firebase добавляет несколько параметров запроса к URL-адресу обработчика действий. Например:
https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy...&lang=fr
Эти параметры определяют задачу управления пользователем, которую выполняет пользователь. Ваша страница обработчика действий с электронной почтой должна обрабатывать следующие параметры запроса:
Параметры режим Действие по управлению пользователями, которое необходимо выполнить. Может принимать одно из следующих значений:
-
resetPassword -
recoverEmail -
verifyEmail
oobCode Одноразовый код, используемый для идентификации и проверки запроса. apiKey Ключ API вашего проекта Firebase, предоставленный для удобства. continueUrl Это необязательный URL-адрес, который позволяет передавать состояние обратно в приложение. Это актуально для режимов сброса пароля и подтверждения электронной почты. При отправке электронного письма для сброса пароля или подтверждения необходимо указать объект ActionCodeSettingsс URL-адресом продолжения, чтобы эта функция была доступна. Это позволяет пользователю продолжить с того места, где он остановился после отправки электронного письма.язык Это необязательный языковой тег BCP47 , представляющий локаль пользователя (например,
fr). Вы можете использовать это значение для предоставления пользователям локализованных страниц обработки действий с электронной почтой.Локализация может быть настроена через консоль Firebase или динамически путем вызова соответствующего клиентского API перед запуском действия отправки электронного письма. Например, с помощью JavaScript:
firebase.auth().languageCode = 'fr';.Для обеспечения единообразного пользовательского опыта убедитесь, что локализация обработчика действий электронной почты соответствует локализации шаблона письма.
В следующем примере показано, как можно обрабатывать параметры запроса в обработчике, работающем в браузере. (Вы также можете реализовать обработчик в виде приложения Node.js, используя аналогичную логику.)
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);
-
Для обработки запросов на сброс пароля сначала проверьте код действия с помощью
verifyPasswordResetCode; затем получите новый пароль от пользователя и передайте его функцииconfirmPasswordReset. Например: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. }); }
Для обработки аннулирования изменений адреса электронной почты сначала проверьте код действия с помощью
checkActionCode, а затем восстановите адрес электронной почты пользователя с помощьюapplyActionCode. Например: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. }); }
Для проверки адреса электронной почты вызовите
applyActionCode. Например: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. }); }
Разместите страницу где-нибудь, например, используйте Firebase Hosting .
Далее необходимо настроить ваш проект Firebase таким образом, чтобы он содержал ссылку на ваш пользовательский обработчик событий электронной почты в письмах, отправляемых пользователям для управления ими.
Добавьте ссылку на свой пользовательский обработчик в шаблоны электронных писем.
Чтобы настроить ваш проект Firebase для использования собственного обработчика событий отправки электронной почты:
В консоли Firebase перейдите в раздел Безопасность > Аутентификация > Вкладка Шаблоны .
В любом из разделов «Типы электронных писем» нажмите на значок карандаша, чтобы отредактировать шаблон электронного письма.
Нажмите «Настроить URL-адрес действия» и укажите URL-адрес обработчика действий с вашей пользовательской электронной почтой.
После сохранения URL-адрес будет использоваться во всех шаблонах электронных писем вашего проекта Firebase.