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

צור משתמש

אתה יוצר משתמש חדש בפרויקט Firebase שלך ​​על ידי קריאה לשיטת createUserWithEmailAndPassword או על ידי כניסה למשתמש בפעם הראשונה באמצעות ספק זהות מאוחד, כגון Google Sign-In או Facebook Login .

אתה יכול גם ליצור משתמשים חדשים מאומתים באמצעות סיסמה מקטע האימות של מסוף Firebase , בדף המשתמשים, או באמצעות ה- Admin SDK .

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

הדרך המומלצת להשיג את המשתמש הנוכחי היא על ידי הגדרת צופה באובייקט Auth:

Web modular API

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 namespaced API

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 modular API

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 namespaced API

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 modular API

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 namespaced API

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 modular API

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 namespaced API

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 modular API

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 namespaced API

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 modular API

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

Web namespaced API

const user = firebase.auth().currentUser;

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

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

אתה יכול לשלוח דוא"ל לאימות כתובת למשתמש בשיטת sendEmailVerification . לדוגמה:

Web modular API

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

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

Web namespaced API

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

אתה יכול להתאים אישית את תבנית הדוא"ל המשמשת בקטע אימות של מסוף Firebase , בדף תבניות דוא"ל. ראה תבניות דוא"ל במרכז העזרה של Firebase.

אפשר גם להעביר מצב באמצעות כתובת URL להמשך כדי להפנות חזרה לאפליקציה בעת שליחת דוא"ל אימות.

בנוסף, תוכל לבצע לוקליזציה של דוא"ל האימות על ידי עדכון קוד השפה במופע Auth לפני שליחת הדוא"ל. לדוגמה:

Web modular API

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 namespaced API

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

הגדר סיסמה של משתמש

אתה יכול להגדיר סיסמה של משתמש בשיטת updatePassword . לדוגמה:

Web modular API

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 namespaced API

const user = firebase.auth().currentUser;
const newPassword = getASecureRandomPassword();

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

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

אתה יכול לשלוח דוא"ל לאיפוס סיסמה למשתמש בשיטת sendPasswordResetEmail . לדוגמה:

Web modular API

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 namespaced API

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

אתה יכול להתאים אישית את תבנית הדוא"ל המשמשת בקטע אימות של מסוף Firebase , בדף תבניות דוא"ל. ראה תבניות דוא"ל במרכז העזרה של Firebase.

אפשר גם להעביר מצב דרך כתובת URL להמשך כדי להפנות חזרה לאפליקציה בעת שליחת אימייל לאיפוס סיסמה.

בנוסף, תוכל לבצע לוקליזציה של דוא"ל איפוס הסיסמה על ידי עדכון קוד השפה במופע ה-Auth לפני שליחת האימייל. לדוגמה:

Web modular API

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 namespaced API

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

אתה יכול גם לשלוח אימיילים לאיפוס סיסמה ממסוף Firebase.

מחק משתמש

ניתן למחוק חשבון משתמש בשיטת delete . לדוגמה:

Web modular API

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

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

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

Web namespaced API

const user = firebase.auth().currentUser;

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

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

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

חלק מהפעולות הרגישות לאבטחה - כגון מחיקת חשבון , הגדרת כתובת דוא"ל ראשית ושינוי סיסמה - מחייבות שהמשתמש נכנס לאחרונה. אם תבצע אחת מהפעולות הללו, והמשתמש נכנס לפני זמן רב מדי, הפעולה נכשלת עם שגיאה. כאשר זה קורה, אימות מחדש את המשתמש על-ידי קבלת אישורי כניסה חדשים מהמשתמש והעברת האישורים ל- reauthenticateWithCredential . לדוגמה:

Web modular API

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 namespaced API

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