إنشاء معالجات إجراءات البريد الإلكتروني المخصصة

تؤدي بعض إجراءات إدارة المستخدم ، مثل تحديث عنوان البريد الإلكتروني للمستخدم وإعادة تعيين كلمة مرور المستخدم ، إلى إرسال رسائل بريد إلكتروني إلى المستخدم. تحتوي رسائل البريد الإلكتروني هذه على روابط يمكن للمستلمين فتحها لإكمال أو إلغاء إجراء إدارة المستخدم. بشكل افتراضي ، ترتبط رسائل البريد الإلكتروني لإدارة المستخدم بمعالج الإجراء الافتراضي ، وهو عبارة عن صفحة ويب مستضافة على عنوان 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 رمز يستخدم لمرة واحدة لتحديد الطلب والتحقق منه
    مفتاح API مفتاح واجهة برمجة تطبيقات مشروع Firebase الخاص بك ، تم توفيره للراحة
    تواصل هذا عنوان URL اختياري يوفر طريقة لإعادة الحالة إلى التطبيق عبر عنوان URL. هذا مناسب لإعادة تعيين كلمة المرور وأوضاع التحقق من البريد الإلكتروني. عند إرسال بريد إلكتروني لإعادة تعيين كلمة المرور أو رسالة بريد إلكتروني للتحقق ، يجب تحديد كائن ActionCodeSettings بعنوان URL للمتابعة حتى يكون هذا متاحًا. هذا يجعل من الممكن للمستخدم الاستمرار من حيث توقف بعد إجراء البريد الإلكتروني.
    لانج

    هذه هي علامة اللغة الاختيارية BCP47 التي تمثل الإعدادات المحلية للمستخدم (على سبيل المثال ، fr ). يمكنك استخدام هذه القيمة لتوفير صفحات معالجة إجراءات البريد الإلكتروني المترجمة للمستخدمين.

    يمكن تعيين الترجمة عبر Firebase Console أو ديناميكيًا عن طريق استدعاء واجهة برمجة تطبيقات العميل المقابلة قبل تشغيل إجراء البريد الإلكتروني. على سبيل المثال ، باستخدام 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 للإجراء ، وحدد عنوان URL لمعالج إجراء البريد الإلكتروني المخصص الخاص بك.

بعد حفظ عنوان URL ، سيتم استخدامه بواسطة جميع قوالب البريد الإلكتروني لمشروع Firebase.