Tạo trình xử lý thao tác tuỳ chỉnh với email

Một số hành động quản lý người dùng, chẳng hạn như cập nhật địa chỉ email của người dùng và đặt lại mật khẩu của người dùng, sẽ khiến email được gửi đến người dùng. Những email này chứa các đường liên kết mà người nhận có thể mở để hoàn tất hoặc huỷ hành động quản lý người dùng. Theo mặc định, email quản lý người dùng sẽ liên kết đến trình xử lý hành động mặc định, đây là một trang web được lưu trữ tại một URL trong miền Lưu trữ Firebase của dự án.

Thay vào đó, bạn có thể tạo và lưu trữ một trình xử lý hành động email tuỳ chỉnh để xử lý tuỳ chỉnh và tích hợp trình xử lý hành động email với trang web của bạn.

Các hành động quản lý người dùng sau đây yêu cầu người dùng hoàn tất hành động bằng trình xử lý hành động qua email:

  • Đặt lại mật khẩu
  • Thu hồi các thay đổi về địa chỉ email – khi người dùng thay đổi địa chỉ email chính của tài khoản, Firebase sẽ gửi một email đến địa chỉ cũ của họ để cho phép họ huỷ thay đổi
  • Xác minh địa chỉ email

Để tuỳ chỉnh trình xử lý hành động qua email của dự án Firebase, bạn phải tạo và lưu trữ một trang web sử dụng SDK JavaScript của Firebase để xác minh tính hợp lệ của yêu cầu và hoàn tất yêu cầu. Sau đó, bạn phải tuỳ chỉnh mẫu email của dự án Firebase để liên kết với trình xử lý thao tác tuỳ chỉnh.

Tạo trang trình xử lý hành động trong email

  1. Firebase thêm một số tham số truy vấn vào URL của trình xử lý hành động khi tạo email quản lý người dùng. Ví dụ:

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

    Các tham số này chỉ định nhiệm vụ quản lý người dùng mà người dùng đang hoàn tất. Trang trình xử lý hành động trong email của bạn phải xử lý các tham số truy vấn sau:

    Thông số
    chế độ

    Hành động quản lý người dùng cần hoàn tất. Có thể là một trong những giá trị sau:

    • resetPassword
    • recoverEmail
    • verifyEmail
    oobCode Mã một lần, dùng để xác định và xác minh yêu cầu
    apiKey Khoá API của dự án Firebase, được cung cấp để thuận tiện cho bạn
    continueUrl Đây là một URL không bắt buộc, cung cấp cách chuyển trạng thái trở lại ứng dụng thông qua một URL. Điều này liên quan đến chế độ đặt lại mật khẩu và xác minh email. Khi gửi email đặt lại mật khẩu hoặc email xác minh, bạn cần chỉ định một đối tượng ActionCodeSettings có URL tiếp nối để có thể sử dụng tính năng này. Điều này giúp người dùng có thể tiếp tục ngay tại nơi họ đã dừng lại sau một hành động trong email.
    lang

    Đây là thẻ ngôn ngữ BCP47 không bắt buộc, đại diện cho ngôn ngữ của người dùng (ví dụ: fr). Bạn có thể sử dụng giá trị này để cung cấp các trang trình xử lý hành động trong email đã bản địa hoá cho người dùng.

    Bạn có thể đặt bản địa hoá thông qua Bảng điều khiển của Firebase hoặc đặt linh động bằng cách gọi API ứng dụng tương ứng trước khi kích hoạt hành động gửi email. Ví dụ: sử dụng JavaScript: firebase.auth().languageCode = 'fr';.

    Để mang lại trải nghiệm nhất quán cho người dùng, hãy đảm bảo bản địa hoá trình xử lý hành động trong email khớp với bản địa hoá của mẫu email.

    Ví dụ sau đây cho thấy cách bạn có thể xử lý các tham số truy vấn trong một trình xử lý dựa trên trình duyệt. (Bạn cũng có thể triển khai trình xử lý dưới dạng ứng dụng Node.js bằng logic tương tự.)

    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. Xử lý yêu cầu đặt lại mật khẩu bằng cách trước tiên xác minh mã hành động bằng verifyPasswordResetCode; sau đó lấy mật khẩu mới từ người dùng và chuyển mật khẩu đó đến confirmPasswordReset. Ví dụ:

    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. Xử lý việc thu hồi thay đổi địa chỉ email bằng cách trước tiên xác minh mã hành động bằng checkActionCode; sau đó khôi phục địa chỉ email của người dùng bằng applyActionCode. Ví dụ:

    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. Xử lý việc xác minh địa chỉ email bằng cách hiển thị nút xác nhận và yêu cầu người dùng nhấp vào nút đó trước khi gọi applyActionCode. Việc yêu cầu người dùng nhấp vào đường liên kết sẽ ngăn các trình quét bảo mật email tự động (tìm nạp trước đường liên kết) sử dụng mã xác minh một lần trước khi người dùng mở trang:

    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. Lưu trữ trang ở một nơi nào đó, ví dụ: sử dụng Firebase Hosting.

Phần phụ trợ của Xác thực Firebase quản lý khoá API được nhúng trong các đường liên kết hành động được tạo, chẳng hạn như tham số apiKey trong URL. Nếu bạn xoay vòng khoá API của dự án hoặc xoá khoá ban đầu được liên kết với Firebase Auth, thì người dùng có thể nhận được đường liên kết có khoá không hợp lệ, dẫn đến lỗi auth/invalid-api-key.

Cách giải quyết:

  • Nếu bạn đang sử dụng Lưu trữ Firebase: Khoá API có thể được lưu vào bộ nhớ đệm trong init.json. Triển khai phiên bản mới của trang web Lưu trữ (firebase deploy --only hosting) để buộc dịch vụ siêu dữ liệu phụ trợ tạo lại cấu hình bằng khoá API đang hoạt động.
  • Nếu cần cập nhật khoá phụ trợ: Vì không thể sửa đổi trực tiếp mối liên kết khoá API phụ trợ bằng bảng điều khiển hoặc SDK, nên bạn phải liên hệ với Nhóm hỗ trợ để yêu cầu cập nhật cấu hình xác thực phụ trợ cho dự án của mình.

Tiếp theo, bạn phải định cấu hình dự án Firebase để liên kết với trình xử lý hành động email tuỳ chỉnh trong email quản lý người dùng.

Cách định cấu hình dự án Firebase để sử dụng trình xử lý hành động email tuỳ chỉnh:

  1. Trong bảng điều khiển Firebase, hãy chuyển đến thẻ Security (Bảo mật) > Authentication (Xác thực) > Templates (Mẫu).

  2. Trong bất kỳ mục Loại email nào, hãy nhấp vào biểu tượng bút chì để chỉnh sửa mẫu email.

  3. Nhấp vào thao tác tuỳ chỉnh URL, rồi chỉ định URL cho trình xử lý thao tác email tuỳ chỉnh của bạn.

Sau khi bạn lưu URL, tất cả mẫu email của dự án Firebase sẽ sử dụng URL này.