ניהול משתמשים ב-Firebase

יצירת משתמש

יש כמה אפשרויות ליצירת משתמש חדש:

קבלת המשתמש שמחובר כרגע

הדרך המומלצת לקבל את המשתמש הנוכחי היא להגדיר אובייקט 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
    // ...
  }
});

שימוש ב-observer מבטיח שאובייקט האימות לא יהיה במצב ביניים – כמו מצב אתחול – כשמקבלים את המשתמש הנוכחי. כשמשתמשים ב-signInWithRedirect, רכיב ה-observer‏ 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, "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
  // ...
});

שליחת הודעת אימות למשתמש

אפשר לשלוח אימייל לאימות כתובת למשתמש באמצעות השיטה 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!
    // ...
  });

אפשר להתאים אישית את תבנית האימייל שבה נעשה שימוש בכרטיסייה תבניות של מסוף Firebase דרך אבטחה > אימות. תוכלו לעיין במאמר בנושא תבניות אימייל במרכז העזרה של 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;
    // ..
  });

אפשר להתאים אישית את תבנית האימייל שבה נעשה שימוש בכרטיסייה תבניות של מסוף Firebase דרך אבטחה > אימות. תוכלו לעיין במאמר בנושא תבניות אימייל במרכז העזרה של 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
  // ...
});

אפשר גם למחוק משתמשים במסוף Firebase בכרטיסייה משתמשים שבקטע אבטחה > אימות.

אימות מחדש של משתמש

כדי לבצע פעולות מסוימות שקשורות לאבטחה, כמו מחיקת חשבון, הגדרת כתובת אימייל ראשית ושינוי סיסמה, המשתמש צריך להיכנס לחשבון שלו לאחרונה. אם מבצעים אחת מהפעולות האלה והמשתמש נכנס לחשבון לפני זמן רב מדי, הפעולה נכשלת ומוצגת שגיאה. במקרה כזה, צריך לבצע אימות מחדש של המשתמש על ידי קבלת פרטי כניסה חדשים מהמשתמש והעברת פרטי הכניסה אל 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 של Firebase CLI. לדוגמה:

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