IDTOKEN reponse is wrong

im doing sign in with apple, using firebase, im runing into a problem where firebase is creating the user on the console but i is doing it with a dash and not the useremail as the identifier.

and i just figure that the reason is because the IDTokenstring is not returning the proper payload, for instances this should be the payload so that firebase can create the user and use the email as the identifier.

however this is what i am getting instead, you can see it is missing email

how can i fix this?

Replies

this is the function getting the payload as idtokenstring and the pyaload gotten from apple doesnt have the email even tho i request in the scope

func handleSignInWithAppleRequest(_ request: ASAuthorizationAppleIDRequest) {
        request.requestedScopes = [.fullName,.email]
        let nonce = randomNonceString()
        
        currentNonce =  nonce
        request.nonce = sha256(nonce)
        
        
    }
    func updateDisplayName(for user: User, with appleIDCredential: ASAuthorizationAppleIDCredential, force: Bool = false) async {
        if let currentDisplayName = Auth.auth().currentUser?.displayName, !currentDisplayName.isEmpty {
          // current user is non-empty, don't overwrite it
        }
        else {
          let changeRequest = user.createProfileChangeRequest()
          changeRequest.displayName = appleIDCredential.displayName()
          do {
            try await changeRequest.commitChanges()
              var displayname = ""
              displayname = Auth.auth().currentUser?.displayName ?? ""
          }
          catch {
            print("Unable to update the user's displayname: \(error.localizedDescription)")
            errorMessage = error.localizedDescription
          }
        }
      }
func handleSignInWithAppleCompletion(_ result: Result<ASAuthorization, Error>) {
        if case .failure(let failure) = result {
            errorMessage = failure.localizedDescription
        } else if case .success(let success) = result {
            if let appleIDCredencials = success.credential as? ASAuthorizationAppleIDCredential {
                
                guard let nonce = currentNonce else {
                    print("invalid State: login callback was recieved, but not login request was sent")
                    fatalError("invalid State: login callback was recieved, but not login request was sent")
                }
                guard let appleIDToken = appleIDCredencials.identityToken else {
                    print("unable to fetch identity token")
                    return
                }
                guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
                    print("unable to serialized token string from data: \(appleIDToken.debugDescription)")
                    return
                }
                let credentials = OAuthProvider.credential(withProviderID: "apple.com", 
                                                           idToken: idTokenString,
                                                           rawNonce: nonce)
                Task {
                    do {
                        let result = try await Auth.auth().signIn(with: credentials)
                        await updateDisplayName(for: result.user, with: appleIDCredencials)
                        let user = result.user
//                        guard user != nil else {
//                            return
//                        }
                        
//
                            guard let email = appleIDCredencials.email   else { return }
//
                            guard let fullName = user.displayName else { return }
                           
//                            var fcmToken: String = ""
                        let token = try await Messaging.messaging().token()
                        print("FCM registration token for logged user google: \(token)")
                        guard let thelangua = Locale.current.language.languageCode else {
                           return print("no languae")
                        }
                        
//                                    fcmToken = token
                        let db =  Firestore.firestore()
                        let updatedDate = Date()
                        let deviceToken = ["token" : token,
                                           "userUid" : user.uid,
                                           "language" : "\(thelangua)",
                                           "timestamp": Timestamp(date: updatedDate)]
                        let fcmtokenRef = db.collection("users").document(user.uid).collection("fcmTokens")
                        fcmtokenRef.whereField("token", isEqualTo: token).getDocuments { snapshot, error in
                            if let err = error {
                                print("Error querying FCM tokens: \(err)")
                            } else if snapshot?.isEmpty == true {
                                // If the query result is empty, it means the token doesn't exist
                                print("FCM token does not exist in the subcollection. Storing the token.")
                                fcmtokenRef.addDocument(data: deviceToken) { error in
                                    if let err = error {
                                        print("error storing device token \(err)")
                                    } else {
                                        print("device token sotre sucessfully.")
                                    }
                                }
                            } else {
                                //Token already exists in the subcollection
                                print("fmc token already exists in the subcollection")
                            }
                        }
//
//
//                            guard let profilePicUrl =     user.profile?.imageURL(withDimension: 320) else { return }
//
                            let values = [GoogleAppleRegistrationKeys.fullName.rawValue: fullName,
                                          GoogleAppleRegistrationKeys.email.rawValue: email,
                                          GoogleAppleRegistrationKeys.userUid.rawValue: user.uid]


                            let  usersRef = db
                            usersRef
                            .collection("users").document(user.uid)
                                .setData(values, merge: true) { (error) in
                                if let err = error  {
                                    print("an err to create document \(err.localizedDescription)")
                                    
                                    //below is an alert when there is an error  creating the DB
                                    //                                        self.popSimpleAlert("Alert", messeage: "failed to saved the values \(String(describing: error?.localizedDescription))")
                                }
                                print("user login with apple id")
                                    

                            }

                           

//                        }
                    } catch {
                        print("error authenticating: \(error.localizedDescription)")
                    }
                }
                
            }
        }
        
    }