פעולות מסוימות של ניהול משתמשים, כמו עדכון כתובת האימייל של המשתמש ואיפוס הסיסמה שלו, גורמות לשליחת אימיילים למשתמש. האימיילים האלה מכילים קישורים שהנמענים יכולים לפתוח כדי להשלים או לבטל את הפעולה של ניהול המשתמשים. כברירת מחדל, הודעות אימייל לניהול משתמשים מקשרות ל-action handler שמוגדר כברירת מחדל, שהוא דף אינטרנט שמתארח בכתובת URL בדומיין של הפרויקט ב-Firebase Hosting.
במקום זאת, אתם יכולים ליצור ולארח handler מותאם אישית של פעולות אימייל כדי לבצע עיבוד בהתאמה אישית ולשלב את ה-handler של פעולות האימייל באתר שלכם.
כדי לבצע את הפעולות הבאות לניהול משתמשים, נדרשת פעולה מהמשתמש להשלים את הפעולה באמצעות handler של פעולות באימייל:
- איפוס סיסמאות
- ביטול שינויים בכתובת האימייל – כשמשתמשים משנים את כתובות האימייל הראשיות של החשבונות שלהם, Firebase שולחת אימייל לכתובות הישנות שלהם שמאפשר להם לבטל את השינוי.
- אימות כתובות אימייל
כדי להתאים אישית את ה-Email Action Handler של הפרויקט ב-Firebase, צריך ליצור ולארח דף אינטרנט שמשתמש ב-Firebase JavaScript SDK כדי לאמת את הבקשה ולהשלים אותה. לאחר מכן, צריך להתאים אישית את תבניות האימייל של הפרויקט ב-Firebase כדי לקשר אותן ל-handler של הפעולה המותאמת אישית.
יצירת דף הטיפול בפעולות באימייל
מערכת Firebase מוסיפה כמה פרמטרים של שאילתה לכתובת ה-URL של ה-action handler כשהיא יוצרת אימיילים לניהול משתמשים. לדוגמה:
https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy...&lang=fr
הפרמטרים האלה מציינים את משימת ניהול המשתמשים שהמשתמש מבצע. דף הטיפול בפעולות באימייל צריך לטפל בפרמטרים הבאים של שאילתות:
פרמטרים מצב הפעולה שצריך לבצע בניהול המשתמשים. יכול להיות אחד מהערכים הבאים:
resetPasswordrecoverEmailverifyEmail
oobCode קוד חד-פעמי שמשמש לזיהוי ולאימות של בקשה apiKey מפתח ה-API של הפרויקט ב-Firebase, שמוצג לנוחותכם continueUrl זו כתובת URL אופציונלית שמאפשרת להעביר את המצב בחזרה לאפליקציה דרך כתובת URL. ההגדרה הזו רלוונטית למצבים של איפוס סיסמה ואימות אימייל. כששולחים אימייל לאיפוס סיסמה או הודעת אימות, צריך לציין אובייקט ActionCodeSettingsעם כתובת URL להמשך כדי שהאפשרות הזו תהיה זמינה. כך המשתמש יכול להמשיך בדיוק מהמקום שבו הוא הפסיק אחרי פעולה באימייל.lang זהו תג השפה האופציונלי BCP47 שמייצג את הלוקאל של המשתמש (לדוגמה,
fr). אתם יכולים להשתמש בערך הזה כדי לספק למשתמשים דפים מקומיים של handler לפעולות באימייל.אפשר להגדיר את הלוקליזציה דרך מסוף Firebase או באופן דינמי על ידי קריאה ל-API המתאים של הלקוח לפני הפעלת פעולת האימייל. לדוגמה, באמצעות JavaScript:
firebase.auth().languageCode = 'fr';.כדי לספק חוויית משתמש עקבית, חשוב לוודא שהשפה של ה-Email Action Handler תואמת לשפה של תבנית האימייל.
בדוגמה הבאה אפשר לראות איך מטפלים בפרמטרים של השאילתה ב-handler שמבוסס על דפדפן. (אפשר גם להטמיע את ה-handler כאפליקציית 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);
כדי לטפל בבקשות לאיפוס סיסמה, קודם צריך לאמת את קוד הפעולה באמצעות
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. }); }
כדי לטפל בביטולים של שינויים בכתובת האימייל, קודם צריך לאמת את קוד הפעולה באמצעות
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. }); }
כדי לטפל באימות של כתובת האימייל, צריך להציג לחצן אישור ולדרוש מהמשתמש ללחוץ עליו לפני הקריאה ל-
applyActionCode. הדרישה שהמשתמש ילחץ על הקישור מונעת מסורקי אבטחה אוטומטיים של אימיילים, שמאחזרים מראש קישורים, לממש קודי אימות חד-פעמיים לפני שהמשתמש פותח את הדף: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. }); }); }מארחים את הדף במקום כלשהו, למשל באמצעות Firebase Hosting.
פתרון בעיות: מפתח API לא עדכני או לא תקין בקישורים לפעולות
ה-backend של אימות ב-Firebase מנהל את מפתח ה-API שמוטמע בקישורי הפעולה שנוצרו, כמו הפרמטר apiKey בכתובת ה-URL. אם תחליפו את מפתחות ה-API של הפרויקט או תמחקו את המפתח שמשויך במקור ל-Firebase Auth, יכול להיות שהמשתמשים יקבלו קישורים עם מפתחות לא תקינים, וכתוצאה מכך יופיעו שגיאות auth/invalid-api-key.
כדי לפתור את הבעיה:
- אם אתם משתמשים באירוח ב-Firebase: יכול להיות שמפתח ה-API נשמר במטמון ב-
init.json. פורסים גרסה חדשה של אתר האירוח (firebase deploy --only hosting) כדי לאלץ את שירות המטא-נתונים של הקצה העורפי ליצור מחדש את ההגדרות עם מפתח ה-API הפעיל. - אם צריך לעדכן את מפתח ה-backend עצמו: אי אפשר לשנות ישירות את המיפוי של מפתח ה-API של ה-backend באמצעות המסוף או ערכות ה-SDK, ולכן צריך לפנות לתמיכה כדי לבקש עדכון של הגדרות האימות של ה-backend בפרויקט.
בשלב הבא, צריך להגדיר את פרויקט Firebase כך שיקשר ל-handler של פעולות האימייל בהתאמה אישית בהודעות האימייל לניהול משתמשים.
קישור ל-handler בהתאמה אישית בתבניות של האימיילים
כדי להגדיר את פרויקט Firebase כך שישתמש ב-handler המותאם אישית של פעולות באימייל:
במסוף Firebase, נכנסים לכרטיסייה Security > Authentication > Templates.
באחד מהרשומות של Email Types, לוחצים על סמל העיפרון כדי לערוך את תבנית האימייל.
לוחצים על התאמה אישית של כתובת ה-URL של פעולה מותאמת אישית ומציינים את כתובת ה-URL של ה-handler של פעולה מותאמת אישית באימייל.
אחרי ששומרים את כתובת ה-URL, היא תשמש את כל תבניות האימייל של הפרויקט ב-Firebase.