I need to implement the function that a Firebase user in my app can delete his/her account if s/he wants to. Here is the account deletion function from Flutter for Firebase:
try {
await FirebaseAuth.instance.currentUser!.delete();
} on FirebaseAuthException catch (e) {
if (e.code == 'requires-recent-login') {
print('The user must reauthenticate before this operation can be executed.');
}
}
In some cases, it may happen that the user had signed in for a long time ago, which will cause the exception of 'requires-recent-login'.
Here is my actual implementation in my app:
Future<String> deleteUserDataFromDatabase() async {
try {
// First, delete the user profile from DB
await _firestore
.collection('app_users')
.doc(_auth!.currentUser!.uid)
.delete();
// Lastly, delete the Authentication profile
User? user = _auth!.currentUser;
await user!.delete();
} on Exception catch (e) {
//print(e);
return Future.value(e.toString());
}
return Future.value('SUCCESS');
}
}
As you see, before deleting the user with the delete() function, I first delete the user profile data from Firestore DB. I need to do so because I set such security rules that the user itself is the only one who can delete his/her profile information in the database, not anyone else.
If the user has recently signed in, there is no problem, everything goes smoothly. But if the user has not recently signed in, then the user profile info is deleted from DB but not the Firebase authentication user account.
It is not an option to delete the Firebase account first, then the user profile information _auth!.currentUser! becomes null after running the await user!.delete().
How can I overcome this problem?
In Flutter, is there a way to detect whether the Firebase user has recently signed in or not? It would be great if it was possible to detect it.
Additionally, is there a way to force user account deletion even if the user has not signed in very recently?