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

تؤدي بعض إجراءات إدارة المستخدمين، مثل تعديل عنوان البريد الإلكتروني للمستخدم و إعادة ضبط كلمة مروره، إلى إرسال رسائل إلكترونية إلى المستخدم. تحتوي هذه الرسائل الإلكترونية على روابط يمكن للمستلمين فتحها لإكمال إجراء إدارة المستخدمين أو إلغائه. ترتبط الرسائل الإلكترونية لإدارة المستخدمين تلقائيًا بمعالج الإجراء التلقائي، وهو صفحة ويب مستضافة على عنوان URL في نطاق "استضافة Firebase" لمشروعك.

يمكنك بدلاً من ذلك إنشاء ونشر معالِج مخصّص لإجراءات البريد الإلكتروني لتنفيذ معالجة مخصّصة ودمج معالِج إجراءات البريد الإلكتروني مع موقعك الإلكتروني.

تتطلّب إجراءات إدارة المستخدمين التالية من المستخدم إكمال الإجراء باستخدام معالِج إجراءات البريد الإلكتروني:

  • إعادة ضبط كلمات المرور
  • إلغاء تغييرات عناوين البريد الإلكتروني: عندما يغيّر المستخدمون عناوين البريد الإلكتروني الأساسية لحساباتهم، تُرسِل Firebase رسالة إلكترونية إلى عناوينهم القديمة تتيح لهم إلغاء التغيير.
  • إثبات ملكية عناوين البريد الإلكتروني

لتخصيص معالِج إجراء الرسالة الإلكترونية لمشروعك على Firebase، عليك إنشاء صفحة ويب تستخدِم حزمة تطوير البرامج (SDK) لـ JavaScript في Firebase ومستضافة عليها للتحقّق من صحة الطلب وإكماله. بعد ذلك، عليك تخصيص نماذج الرسائل الإلكترونية لمشروعك على Firebase لربطها بمعالج الإجراءات المخصّص.

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

  1. تُضيف Firebase العديد من مَعلمات طلب البحث إلى عنوان URL الخاص بمعالج الإجراءات عند إنشاء رسائل إلكترونية لإدارة المستخدمين. على سبيل المثال:

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

    وتحدِّد هذه المَعلمات مهمة إدارة المستخدمين التي يُكمِلها المستخدم. يجب أن تعالج صفحة معالِج إجراءات الرسائل الإلكترونية مَعلمات الطلب التالية:

    المَعلمات
    الوضع

    إجراء إدارة المستخدمين المطلوب إكماله يمكن أن تكون إحدى القيم التالية:

    • resetPassword
    • recoverEmail
    • verifyEmail
    oobCode رمز يصلح للاستخدام مرة واحدة، ويُستخدَم لتحديد طلب والتحقّق منه
    apiKey مفتاح واجهة برمجة التطبيقات لمشروعك على Firebase، مقدَّم لتسهيل الاستخدام
    continueUrl هذا عنوان URL اختياري يقدّم طريقة لنقل الحالة مرة أخرى إلى التطبيق من خلال عنوان URL. يرتبط ذلك بوضعَي إعادة ضبط كلمة المرور والتحقّق من البريد الإلكتروني. عند إرسال رسالة إلكترونية لإعادة ضبط كلمة المرور أو رسالة إلكترونية لإثبات الهوية، يجب تحديد عنصر ActionCodeSettings باستخدام عنوان URL للمتابعة لكي يكون هذا الخيار متاحًا. يتيح ذلك للمستخدم مواصلة الإجراء من حيث توقّفه بعد إجراء اتّباع رسالة إلكترونية.
    lang

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

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

    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

    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. انتقِل إلى صفحة نماذج الرسائل الإلكترونية في قسم Auth.
  3. في أيّ من إدخالات أنواع الرسائل الإلكترونية، انقر على رمز القلم الرصاص لتعديل ملف نماذج الرسائل الإلكترونية.
  4. انقر على تخصيص عنوان URL للإجراء، وحدِّد عنوان URL لمعالج الإجراء المخصّص للبريد الإلكتروني.

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