Membuat pengendali tindakan email kustom

Beberapa tindakan pengelolaan pengguna, seperti mengupdate alamat email dan menyetel ulang sandi pengguna, akan menyebabkan pengiriman email ke pengguna tersebut. Penerima dapat membuka link yang ada di dalam email tersebut untuk menyelesaikan atau membatalkan tindakan pengelolaan pengguna. Secara default, link dalam email pengelolaan pengguna menuju ke pengendali tindakan default, yaitu halaman web yang dihosting di URL pada domain Firebase Hosting project Anda.

Anda dapat membuat dan menghosting pengendali tindakan email kustom untuk melakukan pemrosesan kustom dan mengintegrasikan pengendali tindakan email tersebut ke situs Anda.

Tindakan pengelolaan pengguna berikut ini mengharuskan pengguna menyelesaikan tindakan menggunakan pengendali tindakan email:

  • Mereset sandi
  • Membatalkan perubahan alamat email—ketika pengguna mengubah alamat email utama akunnya, Firebase akan mengirim email ke alamat lama pengguna agar pengguna tersebut dapat membatalkan perubahan
  • Memverifikasi alamat email

Untuk menyesuaikan pengendali tindakan email project Firebase, Anda harus membuat dan menghosting halaman web yang menggunakan Firebase JavaScript SDK untuk memverifikasi validitas permintaan dan menyelesaikan permintaan tersebut. Kemudian, Anda harus menyesuaikan template email project Firebase agar memiliki link ke pengendali tindakan kustom Anda.

Membuat halaman pengendali tindakan email

  1. Firebase menambahkan beberapa parameter kueri ke URL pengendali tindakan ketika membuat email pengelolaan pengguna. Contoh:

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

    Parameter berikut ini menentukan tugas pengelolaan pengguna yang diselesaikan pengguna. Halaman pengendali tindakan email Anda harus menangani parameter kueri berikut ini:

    Parameter
    mode

    Tindakan pengelolaan pengguna yang akan diselesaikan. Dapat berupa salah satu dari nilai berikut ini:

    • resetPassword
    • recoverEmail
    • verifyEmail
    oobCode Kode sekali pakai yang digunakan untuk mengidentifikasi dan memverifikasi permintaan
    apiKey Kunci API project Firebase Anda yang diberikan untuk kemudahan
    continueUrl Ini adalah URL opsional yang memberikan cara untuk meneruskan status kembali ke aplikasi melalui URL. Parameter ini relevan dengan mode reset sandi dan verifikasi email. Agar parameter ini tersedia, saat mengirimkan email reset sandi atau email verifikasi, Anda perlu menentukan continue URL untuk objek ActionCodeSettings. Dengan demikian, pengguna dapat langsung melanjutkan aktivitasnya lagi setelah tindakan email selesai.
    lang

    Ini adalah tag bahasa BCP47 opsional yang mewakili lokalitas pengguna (misalnya, fr). Anda dapat menggunakan nilai ini untuk menyediakan halaman pengendali tindakan email yang sudah dilokalkan bagi pengguna.

    Pelokalan dapat disetel melalui Firebase Console atau secara dinamis dengan memanggil API klien yang sesuai sebelum memicu tindakan email. Misalnya dengan menggunakan JavaScript: firebase.auth().languageCode = 'fr';.

    Agar pengalaman pengguna konsisten, pastikan pelokalan pengendali tindakan email menggunakan template email yang sama.

    Contoh berikut menunjukkan cara menangani parameter kueri di pengendali berbasis browser. (Anda juga dapat menerapkan pengendali sebagai aplikasi Node.js menggunakan logika serupa.)

    API modular 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': "YOU_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);

    API dengan namespace 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. Tangani permintaan reset sandi dengan memverifikasi kode tindakan terlebih dahulu menggunakan verifyPasswordResetCode; lalu dapatkan sandi baru dari pengguna dan teruskan ke confirmPasswordReset. Contoh:

    API modular 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.
      });
    }

    API dengan namespace 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. Tangani pembatalan perubahan alamat email dengan memverifikasi kode tindakan terlebih dahulu menggunakan checkActionCode, lalu pulihkan alamat email pengguna menggunakan applyActionCode. Contoh:

    API modular 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.
      });
    }

    API dengan namespace 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. Tangani verifikasi alamat email dengan memanggil applyActionCode. Contoh:

    API modular 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.
      });
    }

    API dengan namespace 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.
      });
    }
  5. Hosting halaman di suatu tempat, misalnya menggunakan Firebase Hosting.

Berikutnya, Anda harus mengonfigurasi project Firebase agar email pengelolaan penggunanya memiliki link ke pengendali tindakan email kustom Anda.

Untuk mengonfigurasi project Firebase agar menggunakan pengendali tindakan email kustom Anda:

  1. Buka project Anda di Firebase console.
  2. Buka halaman Email Templates di bagian Auth.
  3. Pada salah satu entri di Email Types, klik ikon pensil untuk mengedit template email.
  4. Klik Customize action URL dan masukkan URL untuk pengendali tindakan email kustom Anda.

Setelah Anda menyimpannya, URL tersebut akan digunakan oleh semua template email project Firebase Anda.