Crea gestori di azioni email personalizzati

Alcune azioni di gestione degli utenti, come l'aggiornamento dell'indirizzo e-mail di un utente e la reimpostazione della password di un utente, comportano l'invio di e-mail all'utente. Queste e-mail contengono collegamenti che i destinatari possono aprire per completare o annullare l'azione di gestione degli utenti. Per impostazione predefinita, le email di gestione degli utenti si collegano al gestore dell'azione predefinito, che è una pagina web ospitata in un URL nel dominio di hosting Firebase del tuo progetto.

Puoi invece creare e ospitare un gestore di azioni e-mail personalizzato per eseguire un'elaborazione personalizzata e integrare il gestore di azioni e-mail con il tuo sito web.

Le seguenti azioni di gestione degli utenti richiedono che l'utente completi l'azione utilizzando un gestore di azioni email:

  • Reimpostazione delle password
  • Revoca delle modifiche all'indirizzo email: quando gli utenti modificano gli indirizzi email principali dei propri account, Firebase invia un'email ai loro vecchi indirizzi che consente loro di annullare la modifica
  • Verifica degli indirizzi e-mail

Per personalizzare il gestore dell'azione email del tuo progetto Firebase, devi creare e ospitare una pagina web che utilizzi l'SDK JavaScript di Firebase per verificare la validità della richiesta e completarla. Quindi, devi personalizzare i modelli di email del tuo progetto Firebase in modo che si colleghino al tuo gestore di azioni personalizzato.

Crea la pagina del gestore dell'azione email

  1. Firebase aggiunge diversi parametri di query all'URL del gestore di azioni quando genera email di gestione degli utenti. Ad esempio:

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

    Questi parametri specificano l'attività di gestione degli utenti che l'utente sta completando. La pagina del gestore dell'azione email deve gestire i seguenti parametri di query:

    Parametri
    modalità

    L'azione di gestione degli utenti da completare. Può essere uno dei seguenti valori:

    • resetPassword
    • recoverEmail
    • verifyEmail
    oobCodice Un codice monouso, utilizzato per identificare e verificare una richiesta
    apiKey La chiave API del tuo progetto Firebase, fornita per praticità
    continuaUrl Si tratta di un URL facoltativo che fornisce un modo per restituire lo stato all'app tramite un URL. Questo è rilevante per la reimpostazione della password e le modalità di verifica e-mail. Quando si invia un'e-mail di reimpostazione della password o un'e-mail di verifica, è necessario specificare un oggetto ActionCodeSettings con un URL continuo affinché sia ​​disponibile. Ciò consente a un utente di continuare esattamente da dove si era interrotto dopo un'azione di posta elettronica.
    lang

    Questo è il tag di lingua BCP47 facoltativo che rappresenta la locale dell'utente (ad esempio, fr ). Puoi utilizzare questo valore per fornire agli utenti pagine del gestore di azioni email localizzate.

    La localizzazione può essere impostata tramite la console Firebase o in modo dinamico chiamando l'API client corrispondente prima di attivare l'azione email. Ad esempio, utilizzando JavaScript: firebase.auth().languageCode = 'fr'; .

    Per un'esperienza utente coerente, assicurati che la localizzazione del gestore dell'azione email corrisponda a quella del modello email.

    L'esempio seguente mostra come gestire i parametri di query in un gestore basato su browser. (Potresti anche implementare il gestore come applicazione Node.js utilizzando una logica simile.)

    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': "YOU_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. Gestisci le richieste di reimpostazione della password verificando prima il codice dell'azione con verifyPasswordResetCode ; quindi ottieni una nuova password dall'utente e passala a confirmPasswordReset . Per esempio:

    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. Gestisci le revoche di modifica dell'indirizzo e-mail verificando prima il codice dell'azione con checkActionCode ; quindi ripristinare l'indirizzo email dell'utente con applyActionCode . Per esempio:

    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. Gestisci la verifica dell'indirizzo email chiamando applyActionCode . Per esempio:

    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. Ospita la pagina da qualche parte, ad esempio usa Firebase Hosting .

Successivamente, devi configurare il tuo progetto Firebase in modo che si colleghi al tuo gestore di azioni e-mail personalizzato nelle sue e-mail di gestione degli utenti.

Per configurare il tuo progetto Firebase in modo che utilizzi il tuo gestore di azioni email personalizzato:

  1. Apri il tuo progetto nella console Firebase .
  2. Vai alla pagina Modelli email nella sezione Auth .
  3. In una qualsiasi delle voci Tipi di email , fai clic sull'icona della matita per modificare il modello di email.
  4. Fai clic su personalizza URL azione e specifica l'URL per il gestore dell'azione email personalizzato.

Dopo aver salvato l'URL, verrà utilizzato da tutti i modelli di email del tuo progetto Firebase.