In this section, we will explore how to manage users in Firebase Authentication. This includes creating, updating, and deleting user accounts, as well as handling user sessions and retrieving user information.

Key Concepts

  1. User Management: The process of handling user accounts, including creation, updates, and deletion.
  2. User Sessions: Managing user login sessions to ensure secure access to your application.
  3. User Information: Retrieving and updating user profile information.

Creating a User

To create a user, you can use the createUserWithEmailAndPassword method provided by Firebase Authentication. This method takes an email and password as parameters and creates a new user account.

Example

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // User created successfully
    var user = userCredential.user;
    console.log("User created: ", user);
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    console.error("Error creating user: ", errorCode, errorMessage);
  });

Explanation

  • firebase.auth().createUserWithEmailAndPassword(email, password): This method creates a new user with the provided email and password.
  • .then((userCredential) => { ... }): If the user is created successfully, the userCredential object contains information about the newly created user.
  • .catch((error) => { ... }): If there is an error during user creation, it is caught and handled here.

Updating User Information

Once a user is created, you might want to update their profile information, such as their display name or profile picture.

Example

var user = firebase.auth().currentUser;

user.updateProfile({
  displayName: "John Doe",
  photoURL: "https://example.com/johndoe/profile.jpg"
}).then(() => {
  // Profile updated successfully
  console.log("User profile updated");
}).catch((error) => {
  // An error occurred
  console.error("Error updating profile: ", error);
});

Explanation

  • firebase.auth().currentUser: Retrieves the currently signed-in user.
  • user.updateProfile({ ... }): Updates the user's profile with the provided information.
  • .then(() => { ... }): If the profile is updated successfully, this block is executed.
  • .catch((error) => { ... }): If there is an error during the update, it is caught and handled here.

Deleting a User

To delete a user account, you can use the delete method on the current user object.

Example

var user = firebase.auth().currentUser;

user.delete().then(() => {
  // User deleted successfully
  console.log("User deleted");
}).catch((error) => {
  // An error occurred
  console.error("Error deleting user: ", error);
});

Explanation

  • firebase.auth().currentUser: Retrieves the currently signed-in user.
  • user.delete(): Deletes the user account.
  • .then(() => { ... }): If the user is deleted successfully, this block is executed.
  • .catch((error) => { ... }): If there is an error during deletion, it is caught and handled here.

Retrieving User Information

You can retrieve information about the currently signed-in user using the currentUser property.

Example

var user = firebase.auth().currentUser;

if (user) {
  // User is signed in
  console.log("User ID: ", user.uid);
  console.log("User Email: ", user.email);
  console.log("User Display Name: ", user.displayName);
  console.log("User Photo URL: ", user.photoURL);
} else {
  // No user is signed in
  console.log("No user is signed in");
}

Explanation

  • firebase.auth().currentUser: Retrieves the currently signed-in user.
  • if (user) { ... }: Checks if a user is signed in.
  • console.log(...): Logs the user's information to the console.

Practical Exercise

Task

  1. Create a new user with an email and password.
  2. Update the user's profile with a display name and photo URL.
  3. Retrieve and log the user's information.
  4. Delete the user account.

Solution

// Step 1: Create a new user
firebase.auth().createUserWithEmailAndPassword("[email protected]", "password123")
  .then((userCredential) => {
    var user = userCredential.user;
    console.log("User created: ", user);

    // Step 2: Update the user's profile
    return user.updateProfile({
      displayName: "Test User",
      photoURL: "https://example.com/testuser/profile.jpg"
    });
  })
  .then(() => {
    var user = firebase.auth().currentUser;
    console.log("User profile updated");

    // Step 3: Retrieve and log the user's information
    console.log("User ID: ", user.uid);
    console.log("User Email: ", user.email);
    console.log("User Display Name: ", user.displayName);
    console.log("User Photo URL: ", user.photoURL);

    // Step 4: Delete the user account
    return user.delete();
  })
  .then(() => {
    console.log("User deleted");
  })
  .catch((error) => {
    console.error("Error: ", error);
  });

Explanation

  • The code follows the steps outlined in the task.
  • Each step is chained using promises to ensure sequential execution.
  • Errors are caught and logged at each step.

Common Mistakes and Tips

  • Incorrect Email Format: Ensure the email is in the correct format when creating a user.
  • Weak Password: Firebase requires a minimum password strength. Ensure the password meets the criteria.
  • User Not Signed In: When updating or deleting a user, ensure the user is signed in.
  • Error Handling: Always handle errors to provide feedback to the user and debug issues.

Conclusion

In this section, we covered how to manage users in Firebase Authentication. You learned how to create, update, and delete user accounts, as well as retrieve user information. These skills are essential for managing user authentication and profiles in your application. In the next module, we will dive into the Firebase Realtime Database and learn how to read and write data.

© Copyright 2024. All rights reserved