AkbarB
AkbarB

Reputation: 530

Deleting a user in Firebase auth and user data collection in Firebase database at the same time using Flutter

In my flutter app, I need to provide the user the option to delete their account. This action should delete the user record from Firebase auth as well as all the related data in Firebase database. I can think of two options here :

  1. Delete the user record from auth first and then delete user data from database. In this case, I get a permission error since the user will be logged out after deletion.
  2. Delete the user data from database first and then delete the user record from auth. In this case, right after user data is deleted and before the user is deleted, the app is still in signed-in state and tries to fetch user data which are deleted now and so I get an error here too.

In both cases, sometimes somehow both user record and user data get deleted but I do get the errors in the process and I can see them in the console.

What can I do to properly delete user and its related data from Firebase auth and database?

Thanks for the help!

Upvotes: 0

Views: 3880

Answers (1)

Nolence
Nolence

Reputation: 2254

My current process is to just delete the user record (user.delete()) and then have a Firebase function to delete their data:

const database = admin.firestore();

export const deleteProfile = functions.auth.user().onDelete(async (user) => {
    const batch = database.batch();
    const profile = profilesCollection.doc(user.uid);

    batch.delete(profile);

    // Any other necessary cleanup
    
    await batch.commit();

    console.log(`Deleted profile ${user.uid}`);
});

Make sure to handle the user.delete() errors appropriately such as requiring reauth.

This has the added benefit that you can delete users from firebase console and have their data cleaned up there too.

Upvotes: 3

Related Questions