Создание пользовательских обработчиков действий электронной почты

Некоторые действия по управлению пользователями, такие как обновление адреса электронной почты пользователя и сброс пароля пользователя, приводят к отправке пользователю электронных писем. Эти электронные письма содержат ссылки, которые получатели могут открыть, чтобы завершить или отменить действие по управлению пользователями. По умолчанию электронные письма для управления пользователями ссылаются на обработчик действий по умолчанию, который представляет собой веб-страницу, размещенную по URL-адресу в домене хостинга Firebase вашего проекта.

Вместо этого вы можете создать и разместить настраиваемый обработчик действий электронной почты для выполнения индивидуальной обработки и интеграции обработчика действий электронной почты с вашим веб-сайтом.

Следующие действия по управлению пользователями требуют, чтобы пользователь выполнил действие с помощью обработчика действий электронной почты:

  • Сброс паролей
  • Отмена изменений адреса электронной почты: когда пользователи меняют основные адреса электронной почты своих учетных записей, Firebase отправляет электронное письмо на их старые адреса, которое позволяет им отменить изменение.
  • Проверка адресов электронной почты

Чтобы настроить обработчик действий электронной почты вашего проекта Firebase, вам необходимо создать и разместить веб-страницу, которая использует Firebase JavaScript SDK для проверки действительности запроса и выполнения запроса. Затем вам необходимо настроить шаблоны электронной почты вашего проекта Firebase, чтобы они были связаны с вашим обработчиком настраиваемых действий.

Создайте страницу обработчика действий электронной почты.

  1. Firebase добавляет несколько параметров запроса в URL-адрес вашего обработчика действий, когда генерирует электронные письма для управления пользователями. Например:

    https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy...&lang=fr

    Эти параметры определяют задачу управления пользователями, которую выполняет пользователь. Страница обработчика действий электронной почты должна обрабатывать следующие параметры запроса:

    Параметры
    режим

    Действие по управлению пользователями, которое необходимо выполнить. Может быть одним из следующих значений:

    • resetPassword
    • recoverEmail
    • verifyEmail
    oobCode Одноразовый код, используемый для идентификации и проверки запроса.
    APIKey Ключ API вашего проекта Firebase, предоставленный для удобства.
    продолжитьURL Это необязательный URL-адрес, который позволяет передать состояние обратно в приложение через URL-адрес. Это относится к режимам сброса пароля и проверки электронной почты. При отправке электронного письма для сброса пароля или электронного письма с подтверждением необходимо указать объект ActionCodeSettings с URL-адресом продолжения, чтобы он был доступен. Это позволяет пользователю продолжить работу с того места, на котором он остановился после действия по электронной почте.
    язык

    Это необязательный языковой тег BCP47 , представляющий локаль пользователя (например, fr ). Вы можете использовать это значение для предоставления пользователям локализованных страниц обработчика действий электронной почты.

    Локализация может быть установлена ​​через консоль Firebase или динамически, вызывая соответствующий клиентский API перед запуском действия по электронной почте. Например, используя JavaScript: firebase.auth().languageCode = 'fr'; .

    Для обеспечения единообразия взаимодействия с пользователем убедитесь, что локализация обработчика действий электронной почты соответствует шаблону электронной почты.

    В следующем примере показано, как можно обрабатывать параметры запроса в обработчике на основе браузера. (Вы также можете реализовать обработчик как приложение Node.js, используя аналогичную логику.)

    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);
  2. Обрабатывайте запросы на сброс пароля, сначала проверяя код действия с verifyPasswordResetCode ; затем получите новый пароль от пользователя и передайте его в confirmPasswordReset . Например:

    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.
      });
    }
  3. Обрабатывайте отзыв изменения адреса электронной почты, сначала проверив код действия с помощью checkActionCode ; затем восстановите адрес электронной почты пользователя с помощью applyActionCode . Например:

    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.
      });
    }
  4. Обработайте проверку адреса электронной почты, вызвав applyActionCode . Например:

    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.
      });
    }
  5. Разместите страницу где-нибудь, например, используйте хостинг Firebase .

Затем вы должны настроить свой проект Firebase так, чтобы он связывался с вашим настраиваемым обработчиком действий по электронной почте в электронных письмах для управления пользователями.

Чтобы настроить проект Firebase для использования собственного обработчика действий электронной почты:

  1. Откройте свой проект в консоли Firebase .
  2. Перейдите на страницу «Шаблоны электронной почты» в раздел «Аутентификация» .
  3. В любой записи «Типы электронной почты» щелкните значок карандаша, чтобы изменить шаблон электронной почты.
  4. Нажмите «Настроить URL-адрес действия» и укажите URL-адрес своего обработчика действий по электронной почте.

После сохранения URL-адреса он будет использоваться во всех шаблонах электронной почты вашего проекта Firebase.