ניהול משתמשים ב-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, הצופה 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!
    // ...
  });

אפשר להתאים אישית את תבנית האימייל שבה משתמשים בכרטיסייה Security ‏> Authentication ‏> Templates במסוף 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;
// 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
  // ...
});

שליחת אימייל לאיפוס הסיסמה

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

אפשר להתאים אישית את תבנית האימייל שבה משתמשים בכרטיסייה Security ‏> Authentication ‏> Templates במסוף 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