Özel e-posta işlem işleyicileri oluşturma

Kullanıcının e-posta adresini güncelleme ve şifresini sıfırlama gibi bazı kullanıcı yönetimi işlemleri, kullanıcıya e-posta gönderilmesine neden olur. Bu e-postalarda, alıcıların kullanıcı yönetimi işlemini tamamlamak veya iptal etmek için açabileceği bağlantılar bulunur. Kullanıcı yönetimi e-postaları varsayılan olarak, projenizin Firebase Hosting alanındaki bir URL'de barındırılan web sayfası olan varsayılan işlem işleyiciye bağlanır.

Bunun yerine, özel işleme yapmak ve e-posta işlemi işleyicisini web sitenize entegre etmek için özel bir e-posta işlemi işleyicisi oluşturup barındırabilirsiniz.

Aşağıdaki kullanıcı yönetimi işlemlerinin, bir e-posta işlem işleyicisi kullanılarak tamamlanması gerekir:

  • Şifreleri sıfırlama
  • E-posta adresi değişikliklerini iptal etme: Kullanıcılar hesaplarının birincil e-posta adreslerini değiştirdiğinde Firebase, eski adreslerine değişikliği geri almalarına olanak tanıyan bir e-posta gönderir.
  • E-posta adreslerini doğrulama

Firebase projenizin e-posta işlemi işleyicisini özelleştirmek için isteğin geçerliliğini doğrulamak ve isteği tamamlamak üzere Firebase JavaScript SDK'sını kullanan bir web sayfası oluşturup barındırmanız gerekir. Ardından, Firebase projenizin e-posta şablonlarını özel işlem işleyicinize bağlanacak şekilde özelleştirmeniz gerekir.

E-posta işlemi işleyici sayfasını oluşturma

  1. Firebase, kullanıcı yönetimi e-postaları oluştururken işlem işleyici URL'nize birkaç sorgu parametresi ekler. Örneğin:

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

    Bu parametreler, kullanıcının tamamlamakta olduğu kullanıcı yönetimi görevini belirtir. E-posta işlem işleyici sayfanız aşağıdaki sorgu parametrelerini işlemelidir:

    Parametreler
    mod

    Tamamlanacak kullanıcı yönetimi işlemi. Aşağıdaki değerlerden biri olabilir:

    • resetPassword
    • recoverEmail
    • verifyEmail
    oobCode Bir isteği tanımlamak ve doğrulamak için kullanılan tek seferlik kod
    apiKey Firebase projenizin kolaylık sağlamak için sunulan API anahtarı
    continueUrl Bu, durumu bir URL aracılığıyla uygulamaya geri iletmenin bir yolunu sağlayan isteğe bağlı bir URL'dir. Bu, şifre sıfırlama ve e-posta doğrulama modları için geçerlidir. Şifre sıfırlama e-postası veya doğrulama e-postası gönderirken bunun kullanılabilmesi için bir devam URL'si içeren ActionCodeSettings nesnesinin belirtilmesi gerekir. Bu sayede kullanıcı, e-posta işleminden sonra tam olarak kaldığı yerden devam edebilir.
    lang

    Bu, kullanıcının yerel ayarını temsil eden isteğe bağlı BCP47 dil etiketidir (ör. fr). Kullanıcılarınıza yerelleştirilmiş e-posta işlemi işleyici sayfaları sunmak için bu değeri kullanabilirsiniz.

    Yerelleştirme, Firebase Console üzerinden veya e-posta işlemi tetiklenmeden önce ilgili istemci API'si çağrılarak dinamik olarak ayarlanabilir. Örneğin, JavaScript kullanarak: firebase.auth().languageCode = 'fr';.

    Tutarlı bir kullanıcı deneyimi için e-posta işlemi işleyici yerelleştirmesinin e-posta şablonuyla eşleştiğinden emin olun.

    Aşağıdaki örnekte, sorgu parametrelerini tarayıcı tabanlı bir işleyicide nasıl işleyebileceğiniz gösterilmektedir. (İşleyiciyi benzer bir mantıkla Node.js uygulaması olarak da uygulayabilirsiniz.)

    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. Şifre sıfırlama isteklerini işlemek için önce verifyPasswordResetCode ile işlem kodunu doğrulayın, ardından kullanıcıdan yeni bir şifre alıp confirmPasswordReset yöntemine iletin. Örneğin:

    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. E-posta adresi değişikliği iptallerini işlemek için önce işlem kodunu checkActionCode ile doğrulayın, ardından kullanıcının e-posta adresini applyActionCode ile geri yükleyin. Örneğin:

    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 yöntemini çağırmadan önce bir onay düğmesi gösterip kullanıcının tıklamasını zorunlu kılarak e-posta adresi doğrulama işlemini gerçekleştirin. Kullanıcının tıklamasını zorunlu kılmak, bağlantıları önceden getiren otomatik e-posta güvenlik tarayıcılarının, kullanıcı sayfayı açmadan önce tek seferlik doğrulama kodlarını kullanmasını engeller:

    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.
        });
      });
    }
    
  5. Sayfayı bir yerde barındırın (ör. Firebase Hosting kullanın).

Firebase Authentication arka ucu, oluşturulan işlem bağlantılarına yerleştirilmiş API anahtarını (ör. URL'deki apiKey parametresi) yönetir. Projenizin API anahtarlarını değiştirirseniz veya başlangıçta Firebase Auth ile ilişkilendirilmiş anahtarı silerseniz kullanıcılarınız geçersiz anahtarlar içeren bağlantılar alabilir ve bu da auth/invalid-api-key hatalarına neden olabilir.

Bu sorunu çözmek için:

  • Firebase Hosting kullanıyorsanız: API anahtarı, init.json içinde önbelleğe alınmış olabilir. Arka uç meta veri hizmetini, yapılandırmayı etkin API anahtarıyla yeniden oluşturmaya zorlamak için barındırma sitenizin (firebase deploy --only hosting) yeni bir sürümünü dağıtın.
  • Arka uç anahtarının kendisinin güncellenmesi gerekiyorsa: Arka uç API anahtarı eşlemesi, konsol veya SDK'lar kullanılarak doğrudan değiştirilemediğinden projenizin arka uç kimlik doğrulama yapılandırmasının güncellenmesini talep etmek için Destek Ekibi ile iletişime geçmeniz gerekir.

Ardından, Firebase projenizi, kullanıcı yönetimi e-postalarında özel e-posta işlemi işleyicinize bağlanacak şekilde yapılandırmanız gerekir.

Firebase projenizi özel e-posta işlemi işleyicinizi kullanacak şekilde yapılandırmak için:

  1. Firebase konsolunda Security (Güvenlik) > Authentication (Kimlik Doğrulama) > Templates (Şablonlar) sekmesine gidin.

  2. E-posta şablonunu düzenlemek için E-posta Türleri girişlerinden herhangi birinde kalem simgesini tıklayın.

  3. İşlem URL'sini özelleştir'i tıklayın ve özel e-posta işlem işleyicinizin URL'sini belirtin.

Kaydettiğiniz URL, Firebase projenizin tüm e-posta şablonları tarafından kullanılır.