Crea un utente
Puoi creare un nuovo utente nel tuo progetto Firebase chiamando il metodo
createUserWithEmailAndPassword
o accedendo per la prima volta a un utente con un'identità federata
come Accedi con Google oppure
Accesso a Facebook.
Puoi anche creare nuovi utenti con autenticazione basata su password dal menu della console Firebase, della pagina Utenti oppure utilizzando il SDK Admin.
Recupera l'utente che ha eseguito l'accesso
Il modo consigliato per ottenere l'utente corrente è impostare un osservatore sulla Oggetto Auth:
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 // ... } });
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 una posizione intermedia
ad esempio l'inizializzazione,
quando ottieni l'utente corrente. Quando
usa signInWithRedirect
, l'osservatore onAuthStateChanged
attende fino
getRedirectResult
si risolve prima dell'attivazione.
Puoi anche richiamare l'utente che ha eseguito l'accesso utilizzando l'currentUser
proprietà. Se un utente non ha eseguito l'accesso, il valore currentUser
è nullo:
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. }
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. }
Recuperare il profilo di un utente
Per ottenere le informazioni del profilo di un utente, utilizza le proprietà di un'istanza di
User
. Ad esempio:
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; }
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; }
Recuperare le informazioni del profilo specifiche del fornitore di un utente
Per ottenere le informazioni del profilo recuperate dai fornitori di servizi di accesso collegati a un
utente, utilizza la proprietà providerData
. Ad esempio:
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); }); }
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); }); }
Aggiornare 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:
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 // ... });
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 // ... });
Impostare l'indirizzo email di un utente
Puoi impostare l'indirizzo email di un utente con il metodo updateEmail
. Ad esempio:
import { getAuth, updateEmail } from "firebase/auth"; const auth = getAuth(); updateEmail(auth.currentUser, "user@example.com").then(() => { // Email updated! // ... }).catch((error) => { // An error occurred // ... });
const user = firebase.auth().currentUser; user.updateEmail("user@example.com").then(() => { // Update successful // ... }).catch((error) => { // An error occurred // ... });
Inviare un'email di verifica a un utente
Puoi inviare un'email di verifica dell'indirizzo a un utente con
sendEmailVerification
. Ad esempio:
import { getAuth, sendEmailVerification } from "firebase/auth"; const auth = getAuth(); sendEmailVerification(auth.currentUser) .then(() => { // Email verification sent! // ... });
firebase.auth().currentUser.sendEmailVerification() .then(() => { // Email verification sent! // ... });
Puoi personalizzare il modello email utilizzato nella sezione Autenticazione di Nella pagina Modelli email della console Firebase. Vedi Modelli email in Centro assistenza Firebase.
È anche possibile passare lo stato tramite un URL di continuazione per reindirizzare nuovamente all'app quando viene inviata un'email di verifica.
Inoltre, puoi localizzare l'email di verifica aggiornando il codice lingua sull'istanza Auth prima di inviarla. Ad esempio:
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // auth.useDeviceLanguage();
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:
import { getAuth, updatePassword } from "firebase/auth"; const auth = getAuth(); const user = auth.currentUser; const newPassword = getASecureRandomPassword(); updatePassword(user, newPassword).then(() => { // Update successful. }).catch((error) => { // An error ocurred // ... });
const user = firebase.auth().currentUser; const newPassword = getASecureRandomPassword(); user.updatePassword(newPassword).then(() => { // Update successful. }).catch((error) => { // An error ocurred // ... });
Invia un'email per la reimpostazione della password
Puoi inviare un'email di reimpostazione della password a un utente con sendPasswordResetEmail
. Ad esempio:
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; // .. });
firebase.auth().sendPasswordResetEmail(email) .then(() => { // Password reset email sent! // .. }) .catch((error) => { var errorCode = error.code; var errorMessage = error.message; // .. });
Puoi personalizzare il modello email utilizzato nella sezione Autenticazione di Nella pagina Modelli email della console Firebase. Consulta la sezione Modelli email nel Centro assistenza Firebase.
È anche possibile passare lo stato tramite un URL di continuazione per reindirizzare nuovamente all'app quando viene inviata un'email di reimpostazione password.
Inoltre, puoi localizzare l'email di reimpostazione della password aggiornando la lingua sull'istanza Auth prima di inviare l'email. Ad esempio:
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // auth.useDeviceLanguage();
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.
Eliminare un utente
Puoi eliminare un account utente con il metodo delete
. Ad esempio:
import { getAuth, deleteUser } from "firebase/auth"; const auth = getAuth(); const user = auth.currentUser; deleteUser(user).then(() => { // User deleted. }).catch((error) => { // An error ocurred // ... });
const user = firebase.auth().currentUser; user.delete().then(() => { // User deleted. }).catch((error) => { // An error ocurred // ... });
Puoi anche eliminare gli utenti dalla sezione Autenticazione della Console Firebase, nella pagina Utenti.
Ri-autenticare un utente
Alcune azioni sensibili per la 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
effettuato l'accesso di recente. Se esegui una di queste azioni e l'utente ha eseguito l'accesso
troppo tempo fa, l'azione non riesce e restituisce un errore.
In questo caso, esegui nuovamente l'autenticazione dell'utente ricevendo nuove credenziali di accesso.
dall'utente e passando le credenziali a reauthenticateWithCredential
.
Ad esempio:
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 // ... });
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 account utente
Puoi importare account utente da un file nel tuo progetto Firebase utilizzando la proprietà
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