Search code examples
iosfirebaseflutterfirebase-authenticationapple-sign-in

Firebase Delete User who signed it with apple correclty


I have implemented the Sign-In-With-Apple with Firebase. And I also have the functionality to delete a user. This is what I do:

  static Future<bool> deleteUser(BuildContext context) async {
    try {
      await BackendService().deleteUser(
        context,
      );

      await currentUser!.delete(); // <-- this actually deleting the user from Auth

      Provider.of<DataProvider>(context, listen: false).reset();

      return true;
    } on FirebaseException catch (error) {
      print(error.message);
      AlertService.showSnackBar(
        title: 'Fehler',
        description: error.message ?? 'Unbekannter Fehler',
        isSuccess: false,
      );
      return false;
    }
  }

As you can see I delete all the users data and finally the user himself from auth.

But Apple still thinks I am using the App. I can see it inside my Settings:

enter image description here

Also when trying to sign in again with apple, it acts like I already have an account. But I just deleted it and there is nothing inside Firebase that says that I still have that account? How can I completely delete an Apple user from Firebase? What am I missing here?


Solution

  • so... Apple does not provide this service. But for my case, the following workaround is working just fine.

    My sign in process:

    1. Check if user signed in before

      // Create an `OAuthCredential` from the credential returned by Apple.
      final oauthCredential = OAuthProvider("apple.com").credential(
        idToken: appleCredential.identityToken,
        rawNonce: rawNonce,
      );
    
      // If you can not access the email property in credential,
      // means that user already signed in with his appleId in the application once before
      bool isAlreadyRegistered = appleCredential.email == null;
    

    Now to the crucial part:

    2. sign in user and check if that uid already exists in Firebase

      final UserCredential result =
          await FirebaseAuth.instance.signInWithCredential(
        oauthCredential,
      );
    
      isAlreadyRegistered = await BackendService.checkIfUserIdExists(
        result.user?.uid ?? '',
      );
    

    checkIfUserIdExists is quite simple as well:

      static Future<bool> checkIfUserIdExists(String userId) async {
        try {
          var collectionRef = FirebaseFirestore.instance.collection(
            BackendKeys.users,
          );
    
          var doc = await collectionRef.doc(userId).get();
          return doc.exists;
        } on FirebaseException catch (e) {
          return false;
        }
      }