יצירת משתמש
כדי ליצור משתמש חדש בפרויקט Firebase, צריך להפעיל את השיטה createUserWithEmailAndPassword
או להתחבר בפעם הראשונה באמצעות ספק זהויות מאוחד, כמו כניסה באמצעות חשבון Google או כניסה באמצעות חשבון Facebook.
אפשר גם ליצור משתמשים חדשים שמאומתים באמצעות סיסמה בקטע Authentication (אימות) במסוף Firebase, בדף Users (משתמשים) או באמצעות Admin SDK.
אחזור המשתמש המחובר הנוכחי
הדרך המומלצת לקבל את המשתמש הנוכחי היא להגדיר משתמש שמתבונן באובייקט 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 // ... } });
השימוש במעקב מבטיח שהאובייקט של Auth לא נמצא במצב ביניים – כמו אתחול – כשמקבלים את המשתמש הנוכחי. כשמשתמשים ב-signInWithRedirect
, הצופה onAuthStateChanged
ממתין עד שהבעיה ב-getRedirectResult
תיפתר לפני שהוא מפעיל את הפונקציה.
אפשר גם לקבל את המשתמש שמחובר כרגע באמצעות המאפיין currentUser
. אם המשתמש לא מחובר לחשבון, הערך של 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. }
אחזור פרופיל של משתמש
כדי לקבל את פרטי הפרופיל של משתמש, משתמשים במאפיינים של מכונה של User
. לדוגמה:
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; }
אחזור פרטי הפרופיל הספציפיים לספק של משתמש
כדי לקבל את פרטי הפרופיל שאוחזרו מספקי הכניסה שמקושרים למשתמש, משתמשים במאפיין providerData
. לדוגמה:
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); }); }
עדכון פרופיל של משתמש
אפשר לעדכן את פרטי הפרופיל הבסיסיים של משתמש – השם המוצג של המשתמש וכתובת ה-URL של תמונת הפרופיל שלו – באמצעות השיטה updateProfile
. לדוגמה:
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 // ... });
הגדרת כתובת האימייל של המשתמש
אפשר להגדיר את כתובת האימייל של משתמש באמצעות השיטה updateEmail
. לדוגמה:
Web
import { getAuth, updateEmail } from "firebase/auth"; const auth = getAuth(); updateEmail(auth.currentUser, "[email protected]").then(() => { // Email updated! // ... }).catch((error) => { // An error occurred // ... });
Web
const user = firebase.auth().currentUser; user.updateEmail("[email protected]").then(() => { // Update successful // ... }).catch((error) => { // An error occurred // ... });
שליחת הודעת אימות למשתמש
אפשר לשלוח למשתמש הודעת אימייל לאימות כתובת באמצעות השיטה sendEmailVerification
. לדוגמה:
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! // ... });
אפשר להתאים אישית את תבנית האימייל שמשמשת בקטע Authentication (אימות) במסוף Firebase, בדף Email Templates (תבניות אימייל). מידע נוסף זמין במאמר תבניות אימייל במרכז העזרה של Firebase.
אפשר גם להעביר את המצב באמצעות כתובת URL להמשך כדי להפנות חזרה לאפליקציה כששולחים אימייל אימות.
בנוסף, אפשר להתאים את הודעת האימות לשפה המקומית על ידי עדכון קוד השפה במכונה של Auth לפני שליחת האימייל. לדוגמה:
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();
הגדרת סיסמה של משתמש
אפשר להגדיר סיסמה של משתמש באמצעות השיטה updatePassword
. לדוגמה:
Web
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 // ... });
Web
const user = firebase.auth().currentUser; const newPassword = getASecureRandomPassword(); user.updatePassword(newPassword).then(() => { // Update successful. }).catch((error) => { // An error ocurred // ... });
שליחת אימייל לאיפוס הסיסמה
אפשר לשלוח אימייל לאיפוס הסיסמה למשתמש באמצעות השיטה sendPasswordResetEmail
. לדוגמה:
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; // .. });
אפשר להתאים אישית את תבנית האימייל שמשמשת בקטע Authentication (אימות) במסוף Firebase, בדף Email Templates (תבניות אימייל). מידע נוסף זמין במאמר תבניות אימייל במרכז העזרה של Firebase.
אפשר גם להעביר את המצב באמצעות כתובת URL להמשך כדי להפנות אוטומטית בחזרה לאפליקציה כששולחים אימייל לאיפוס הסיסמה.
בנוסף, אפשר להתאים את האימייל לאיפיון שלכם על ידי עדכון קוד השפה במכונה של Auth לפני שליחת האימייל. לדוגמה:
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();
אפשר גם לשלוח אימיילים לאיפוס סיסמה מהמסוף Firebase.
מחיקת משתמש
אפשר למחוק חשבון משתמש באמצעות השיטה delete
. לדוגמה:
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 // ... });
אפשר גם למחוק משתמשים מהקטע Authentication (אימות) במסוף Firebase, בדף Users (משתמשים).
אימות מחדש של משתמש
כדי לבצע פעולות מסוימות שקשורות לאבטחה, כמו מחיקת חשבון, הגדרת כתובת אימייל ראשית ושינוי סיסמה, המשתמש צריך להיכנס לחשבון לאחרונה. אם מבצעים אחת מהפעולות האלה והמשתמש נכנס לחשבון לפני זמן רב מדי, הפעולה נכשלת עם שגיאה.
במקרה כזה, מבצעים אימות מחדש של המשתמש על ידי קבלת פרטי כניסה חדשים מהמשתמש והעברת פרטי הכניסה אל reauthenticateWithCredential
.
לדוגמה:
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 // ... });
ייבוא חשבונות משתמשים
אפשר לייבא חשבונות משתמשים מקובץ לפרויקט Firebase באמצעות הפקודה auth:import
ב-CLI של Firebase. לדוגמה:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14