From 2e6df97608d0f654a477719e5185518e16f877be Mon Sep 17 00:00:00 2001 From: NiraliSonani Date: Mon, 16 Dec 2024 13:01:25 +0530 Subject: [PATCH] Fix: after login with same email getting nil user --- Data/Data/Repository/UserRepository.swift | 4 ++ Data/Data/Store/UserStore.swift | 39 +++++++++++++++++++ .../EmailLogin/EmailLoginViewModel.swift | 32 +++++++++++---- 3 files changed, 68 insertions(+), 7 deletions(-) diff --git a/Data/Data/Repository/UserRepository.swift b/Data/Data/Repository/UserRepository.swift index d4c6a8628..3e50c76fc 100644 --- a/Data/Data/Repository/UserRepository.swift +++ b/Data/Data/Repository/UserRepository.swift @@ -31,6 +31,10 @@ public class UserRepository: ObservableObject { public func fetchUserBy(userID: String) async throws -> AppUser? { return try await store.fetchUserBy(id: userID) } + + public func fetchUserBy(email: String) async throws -> AppUser? { + return try await store.fetchUserBy(email: email) + } public func fetchLatestUserBy(userID: String, completion: @escaping (AppUser?) -> Void) { store.fetchLatestUserBy(id: userID) { user in diff --git a/Data/Data/Store/UserStore.swift b/Data/Data/Store/UserStore.swift index 06b308aa7..2cc695c48 100644 --- a/Data/Data/Store/UserStore.swift +++ b/Data/Data/Store/UserStore.swift @@ -6,6 +6,7 @@ // import FirebaseFirestore +import FirebaseAuth class UserStore: ObservableObject { @@ -45,6 +46,19 @@ class UserStore: ObservableObject { } } + func fetchUserBy(email: String) async throws -> AppUser? { + let snapshot = try await usersCollection.whereField("email_id", isEqualTo: email).getDocuments() + + if let document = snapshot.documents.first { + let fetchedUser = try document.data(as: AppUser.self) + LogD("UserStore: \(#function) User fetched successfully by email.") + return fetchedUser + } else { + LogE("UserStore: \(#function) No user found for email: \(email).") + return nil + } + } + func fetchLatestUserBy(id: String, completion: @escaping (AppUser?) -> Void) { listener?.remove() listener = usersCollection.document(id).addSnapshotListener { snapshot, error in @@ -74,4 +88,29 @@ class UserStore: ObservableObject { func deactivateUserAfterDelete(userId: String) async throws { try await usersCollection.document(userId).updateData(["is_active": false]) } + + func deleteAccount() { + // Get the currently signed-in user + guard let user = Auth.auth().currentUser else { + print("No user is currently signed in.") + return + } + + // Delete the user's account + user.delete { error in + if let error { + // Handle error (e.g., user may need to reauthenticate) + print("Error deleting account: \(error.localizedDescription)") + + // Example: Reauthentication may be required + if let authError = error as? NSError, + authError.code == AuthErrorCode.requiresRecentLogin.rawValue { + print("User needs to reauthenticate before deleting their account.") + // Call a reauthentication flow here + } + } else { + print("User account deleted successfully.") + } + } + } } diff --git a/Splito/UI/Login/EmailLogin/EmailLoginViewModel.swift b/Splito/UI/Login/EmailLogin/EmailLoginViewModel.swift index 11b6e5beb..ceda93ac0 100644 --- a/Splito/UI/Login/EmailLogin/EmailLoginViewModel.swift +++ b/Splito/UI/Login/EmailLogin/EmailLoginViewModel.swift @@ -42,18 +42,36 @@ public class EmailLoginViewModel: BaseViewModel, ObservableObject { func onLoginClick() { guard validateEmailAndPassword() else { return } - - isLoginInProgress = true - FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password) { [weak self] result, error in - guard let self else { return } - isLoginInProgress = false - self.handleAuthResponse(result: result, error: error, isLogin: true) + + Task { + do { + isLoginInProgress = true + + if let user = try await userRepository.fetchUserBy(email: email) { + if user.loginType != .Email { + isLoginInProgress = false + showAlertFor(title: "Error", message: "This account already exists with a different login method.") + return + } + + FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password) { [weak self] result, error in + self?.isLoginInProgress = false + self?.handleAuthResponse(result: result, error: error, isLogin: true) + } + } else { + isLoginInProgress = false + LogE("EmailLoginViewModel: \(#function) No user found with this email.") + } + } catch { + isLoginInProgress = false + LogE("EmailLoginViewModel: \(#function) Error fetching user: \(error).") + } } } private func handleAuthResponse(result: AuthDataResult?, error: Error?, isLogin: Bool) { if let error { - LogE("EmailLoginViewModel: \(#function) Error during \(isLogin ? "login" : "sign up"): \(error)") + LogE("EmailLoginViewModel: \(#function) Error during \(isLogin ? "login" : "sign up"): \(error).") handleFirebaseAuthErrors(error) } else if let result { let user = AppUser(id: result.user.uid, firstName: "", lastName: "",