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

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

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

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

  • Сброс паролей
  • Отмена изменений адреса электронной почты. Когда пользователи меняют основные адреса электронной почты своих аккаунтов, 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, предоставленный для удобства.
    continueUrl Это необязательный URL, который позволяет передавать состояние обратно в приложение. Это относится к режимам сброса пароля и подтверждения адреса электронной почты. При отправке письма для сброса пароля или письма с подтверждением необходимо указать объект ActionCodeSettings с URL продолжения. Это позволяет пользователю продолжить работу с того места, на котором он остановился.
    lang

    Необязательный языковой тег 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);
  2. Обрабатывайте запросы на сброс пароля, сначала проверяя код действия с помощью 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.
      });
    }
  3. Чтобы обработать отмену изменения адреса электронной почты, сначала проверьте код действия с помощью 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.
      });
    }
  4. Чтобы подтвердить адрес электронной почты, покажите кнопку подтверждения и попросите пользователя нажать ее, прежде чем вызывать applyActionCode. Это позволяет предотвратить автоматическое использование одноразовых кодов подтверждения сканерами безопасности электронной почты, которые предварительно загружают ссылки, до того, как пользователь откроет страницу.

    Web

    import { applyActionCode } from "firebase/auth";
    
    function handleVerifyEmail(auth, actionCode, continueUrl, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
      // Show the confirmation button and apply the action code only after
      // the user clicks it.
      const confirmButton = document.getElementById('confirm-verify-email');
      if (!confirmButton) {
        return;
      }
      confirmButton.hidden = false;
      confirmButton.addEventListener('click', () => {
        confirmButton.disabled = true;
        applyActionCode(auth, actionCode).then(() => {
          // Email address has been verified. Display a confirmation
          // message, and if continueUrl is available, provide a button
          // that redirects back to the app.
        }).catch((error) => {
          confirmButton.disabled = false;
          // Code is invalid, expired, or failed due to a network error.
          // Ask the user to verify their email address again if needed.
        });
      });
    }
    

    Web

    function handleVerifyEmail(auth, actionCode, continueUrl, lang) {
      // Localize the UI to the selected language as determined by the lang
      // parameter.
      // Show the confirmation button and apply the action code only after
      // the user clicks it.
      var confirmButton = document.getElementById('confirm-verify-email');
      if (!confirmButton) {
        return;
      }
      confirmButton.hidden = false;
      confirmButton.addEventListener('click', function() {
        confirmButton.disabled = true;
        auth.applyActionCode(actionCode).then(function() {
          // Email address has been verified. Display a confirmation
          // message, and if continueUrl is available, provide a button
          // that redirects back to the app.
        }).catch(function(error) {
          confirmButton.disabled = false;
          // Code is invalid, expired, or failed due to a network error.
          // Ask the user to verify their email address again if needed.
        });
      });
    }
    
  5. Разместите страницу в интернете, например с помощью Firebase Hosting.

Бэкенд Firebase Authentication управляет ключом API, встроенным в сгенерированные ссылки для действий, например параметром apiKey в URL. Если вы измените ключи API проекта или удалите ключ, который изначально был связан с Firebase Auth, пользователи могут получить ссылки с недействительными ключами, что приведет к ошибкам auth/invalid-api-key.

Чтобы решить проблему:

  • Если вы используете Firebase Hosting, ключ API может быть кеширован в init.json. Разверните новую версию сайта Hosting (firebase deploy --only hosting), чтобы заставить сервис метаданных бэкенда повторно сгенерировать конфигурацию с активным ключом API.
  • Если нужно обновить сам ключ бэкенда. Поскольку сопоставление ключа API бэкенда нельзя изменить напрямую с помощью консоли или SDK, вам необходимо обратиться в службу поддержки, чтобы запросить обновление конфигурации аутентификации бэкенда для вашего проекта.

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

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

  1. В консоли Firebase перейдите в раздел Security (Безопасность) > Authentication (Аутентификация) > Templates (Шаблоны).

  2. В любом из полей Типы электронных писем нажмите на значок карандаша, чтобы изменить шаблон электронного письма.

  3. Нажмите Настроить URL настраиваемого действия и укажите URL обработчика настраиваемых действий.

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