Gestisci gli utenti in Firebase

Crea un utente

Per creare un nuovo utente, hai a disposizione le seguenti opzioni:

  • Dalla tua app: crea un nuovo utente nel tuo progetto Firebase chiamando il metodo createUserWithEmailAndPassword o eseguendo l'accesso di un utente per la prima volta utilizzando un provider di identità federate, come Accedi con Google o Accesso con Facebook.

  • Nella console Firebase: crea un nuovo utente autenticato con password nella scheda Sicurezza > Autenticazione > Utenti.

Recupera l'utente che ha eseguito l'accesso

Il modo consigliato per ottenere l'utente corrente è impostare un osservatore sull'oggetto Auth:

Web

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/auth.user
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

Web

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/v8/firebase.User
    var uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

Utilizzando un osservatore, ti assicuri che l'oggetto Auth non si trovi in uno stato intermedio, ad esempio l'inizializzazione, quando recuperi l'utente corrente. Quando utilizzi signInWithRedirect, l'observer onAuthStateChanged attende che getRedirectResult venga risolto prima di attivarsi.

Puoi anche recuperare l'utente che ha eseguito l'accesso utilizzando la proprietà currentUser. Se un utente non ha eseguito l'accesso, currentUser è null:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

if (user) {
  // User is signed in, see docs for a list of available properties
  // https://firebase.google.com/docs/reference/js/auth.user
  // ...
} else {
  // No user is signed in.
}

Web

const user = firebase.auth().currentUser;

if (user) {
  // User is signed in, see docs for a list of available properties
  // https://firebase.google.com/docs/reference/js/v8/firebase.User
  // ...
} else {
  // No user is signed in.
}

Recupera il profilo di un utente

Per ottenere le informazioni del profilo di un utente, utilizza le proprietà di un'istanza di User. Ad esempio:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;
if (user !== null) {
  // The user object has basic properties such as display name, email, etc.
  const displayName = user.displayName;
  const email = user.email;
  const photoURL = user.photoURL;
  const emailVerified = user.emailVerified;

  // The user's ID, unique to the Firebase project. Do NOT use
  // this value to authenticate with your backend server, if
  // you have one. Use User.getToken() instead.
  const uid = user.uid;
}

Web

const user = firebase.auth().currentUser;
if (user !== null) {
  // The user object has basic properties such as display name, email, etc.
  const displayName = user.displayName;
  const email = user.email;
  const photoURL = user.photoURL;
  const emailVerified = user.emailVerified;

  // The user's ID, unique to the Firebase project. Do NOT use
  // this value to authenticate with your backend server, if
  // you have one. Use User.getIdToken() instead.
  const uid = user.uid;
}

Recupera le informazioni del profilo di un utente specifiche del provider

Per ottenere le informazioni del profilo recuperate dai provider di accesso collegati a un utente, utilizza la proprietà providerData. Ad esempio:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

if (user !== null) {
  user.providerData.forEach((profile) => {
    console.log("Sign-in provider: " + profile.providerId);
    console.log("  Provider-specific UID: " + profile.uid);
    console.log("  Name: " + profile.displayName);
    console.log("  Email: " + profile.email);
    console.log("  Photo URL: " + profile.photoURL);
  });
}

Web

const user = firebase.auth().currentUser;

if (user !== null) {
  user.providerData.forEach((profile) => {
    console.log("Sign-in provider: " + profile.providerId);
    console.log("  Provider-specific UID: " + profile.uid);
    console.log("  Name: " + profile.displayName);
    console.log("  Email: " + profile.email);
    console.log("  Photo URL: " + profile.photoURL);
  });
}

Aggiorna il profilo di un utente

Puoi aggiornare le informazioni di base del profilo di un utente, ovvero il nome visualizzato e l'URL della foto del profilo, con il metodo updateProfile. Ad esempio:

Web

import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
updateProfile(auth.currentUser, {
  displayName: "Jane Q. User", photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
  // Profile updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Web

const user = firebase.auth().currentUser;

user.updateProfile({
  displayName: "Jane Q. User",
  photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
  // Update successful
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});  

Imposta l'indirizzo email di un utente

Puoi impostare l'indirizzo email di un utente con il metodo updateEmail. Ad esempio:

Web

import { getAuth, updateEmail } from "firebase/auth";
const auth = getAuth();
updateEmail(auth.currentUser, "user@example.com").then(() => {
  // Email updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Web

const user = firebase.auth().currentUser;

user.updateEmail("user@example.com").then(() => {
  // Update successful
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Invia un'email di verifica a un utente

Puoi inviare un'email di verifica dell'indirizzo a un utente con il metodo sendEmailVerification. Ad esempio:

Web

import { getAuth, sendEmailVerification } from "firebase/auth";

const auth = getAuth();
sendEmailVerification(auth.currentUser)
  .then(() => {
    // Email verification sent!
    // ...
  });

Web

firebase.auth().currentUser.sendEmailVerification()
  .then(() => {
    // Email verification sent!
    // ...
  });

Puoi personalizzare il modello di email utilizzato nella scheda Sicurezza > Autenticazione > Modelli della console Firebase. Consulta Modelli di email nel Centro assistenza Firebase.

È anche possibile passare lo stato tramite un URL continuo per reindirizzare all'app quando si invia un'email di verifica.

Inoltre, puoi localizzare l'email di verifica aggiornando il codice della lingua nell'istanza Auth prima di inviare l'email. Ad esempio:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
auth.languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// auth.useDeviceLanguage();

Web

firebase.auth().languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

Imposta la password di un utente

Puoi impostare la password di un utente con il metodo updatePassword. Ad esempio:

Web

import { getAuth, updatePassword } from "firebase/auth";

const auth = getAuth();

const user = auth.currentUser;
// Add your own function here to read the user's entered password, or generate a new one
const newPassword = getASecureRandomPassword();

updatePassword(user, newPassword).then(() => {
  // Update successful.
}).catch((error) => {
  // An error ocurred
  // ...
});

Web

const user = firebase.auth().currentUser;
// Add your own function here to read the user's entered password, or generate a new one
const newPassword = getASecureRandomPassword();

user.updatePassword(newPassword).then(() => {
  // Update successful.
}).catch((error) => {
  // An error ocurred
  // ...
});

Invia un'email di reimpostazione password

Puoi inviare un'email di reimpostazione della password a un utente con il metodo sendPasswordResetEmail. Ad esempio:

Web

import { getAuth, sendPasswordResetEmail } from "firebase/auth";

const auth = getAuth();
sendPasswordResetEmail(auth, email)
  .then(() => {
    // Password reset email sent!
    // ..
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    // ..
  });

Web

firebase.auth().sendPasswordResetEmail(email)
  .then(() => {
    // Password reset email sent!
    // ..
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // ..
  });

Puoi personalizzare il modello di email utilizzato nella scheda Sicurezza > Autenticazione > Modelli della console Firebase. Consulta Modelli di email nel Centro assistenza Firebase.

È anche possibile passare lo stato tramite un URL continuo per reindirizzare l'utente all'app quando invii un'email di reimpostazione password.

Inoltre, puoi localizzare l'email di reimpostazione della password aggiornando il codice della lingua nell'istanza Auth prima di inviare l'email. Ad esempio:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
auth.languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// auth.useDeviceLanguage();

Web

firebase.auth().languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

Puoi anche inviare email di reimpostazione della password dalla console Firebase.

Elimina un utente

Puoi eliminare un account utente con il metodo delete. Ad esempio:

Web

import { getAuth, deleteUser } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

deleteUser(user).then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});

Web

const user = firebase.auth().currentUser;

user.delete().then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});

Puoi anche eliminare gli utenti nella console Firebase nella scheda Sicurezza > Autenticazione > Utenti.

Ripeti l'autenticazione di un utente

Alcune azioni sensibili dal punto di vista della sicurezza, come l'eliminazione di un account, l'impostazione di un indirizzo email principale e la modifica di una password, richiedono che l'utente abbia eseguito l'accesso di recente. Se esegui una di queste azioni e l'utente ha eseguito l'accesso troppo tempo fa, l'azione non va a buon fine e viene visualizzato un errore. In questo caso, autentica nuovamente l'utente ottenendo nuove credenziali di accesso dall'utente e trasmettendole a reauthenticateWithCredential. Ad esempio:

Web

import { getAuth, reauthenticateWithCredential } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

reauthenticateWithCredential(user, credential).then(() => {
  // User re-authenticated.
}).catch((error) => {
  // An error ocurred
  // ...
});

Web

const user = firebase.auth().currentUser;

// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

user.reauthenticateWithCredential(credential).then(() => {
  // User re-authenticated.
}).catch((error) => {
  // An error occurred
  // ...
});

Importa gli account utente

Puoi importare gli account utente da un file nel tuo progetto Firebase utilizzando il comando auth:import dell'interfaccia a riga di comando di Firebase. Ad esempio:

firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14