צור מטפלי פעולות דוא"ל מותאמים אישית

פעולות מסוימות של ניהול משתמשים, כגון עדכון כתובת אימייל של משתמש ואיפוס סיסמה של משתמש, גורמות לשליחת מיילים למשתמש. הודעות דוא"ל אלה מכילות קישורים שהנמענים יכולים לפתוח כדי להשלים או לבטל את פעולת ניהול המשתמשים. כברירת מחדל, הודעות דוא"ל לניהול משתמשים מקשרות למטפל בפעולות המוגדרות כברירת מחדל, שהוא דף אינטרנט המתארח בכתובת URL בדומיין Firebase Hosting של הפרויקט שלך.

במקום זאת, תוכל ליצור ולארח מטפל בפעולות דוא"ל מותאם אישית כדי לבצע עיבוד מותאם אישית ולשלב את מטפל פעולות הדוא"ל עם האתר שלך.

פעולות ניהול המשתמשים הבאות מחייבות את המשתמש להשלים את הפעולה באמצעות מטפל בפעולות דואר אלקטרוני:

  • איפוס סיסמאות
  • ביטול שינויים בכתובת דוא"ל - כאשר משתמשים משנים את כתובות האימייל הראשיות של חשבונותיהם, Firebase שולח דוא"ל לכתובות הישנות שלהם המאפשרות להם לבטל את השינוי
  • אימות כתובות אימייל

כדי להתאים אישית את המטפל בפעולות הדוא"ל של פרויקט Firebase שלך, עליך ליצור ולארח דף אינטרנט המשתמש ב-SDK של Firebase JavaScript כדי לאמת את תקפות הבקשה ולהשלים את הבקשה. לאחר מכן, עליך להתאים אישית את תבניות הדוא"ל של פרויקט 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 אופציונלית המספקת דרך להעביר מצב חזרה לאפליקציה באמצעות כתובת URL. זה רלוונטי למצבי איפוס סיסמה ואימות דוא"ל. בעת שליחת אימייל לאיפוס סיסמה או דוא"ל אימות, יש לציין אובייקט ActionCodeSettings עם כתובת URL להמשך כדי שזה יהיה זמין. זה מאפשר למשתמש להמשיך היכן שהפסיק לאחר פעולת אימייל.
    lang

    זהו תג השפה האופציונלי 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 Hosting .

לאחר מכן, עליך להגדיר את פרויקט Firebase שלך ​​כך שיקשר למטפל בפעולות הדוא"ל המותאם אישית שלך בדוא"ל ניהול המשתמשים שלו.

כדי להגדיר את פרויקט Firebase שלך ​​לשימוש במטפל בפעולות האימייל המותאם אישית שלך:

  1. פתח את הפרויקט שלך במסוף Firebase .
  2. עבור לדף תבניות דוא"ל במקטע אימות .
  3. בכל אחד מהערכים של סוגי דוא"ל , לחץ על סמל העיפרון כדי לערוך את תבנית הדוא"ל.
  4. לחץ על התאמה אישית של כתובת URL של פעולה וציין את כתובת האתר למטפל בפעולות הדוא"ל המותאם אישית שלך.

לאחר שמירת כתובת האתר, היא תשמש את כל תבניות האימייל של פרויקט Firebase שלך.