Skip to content

Commit

Permalink
Fix: after login with same email getting nil user
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-nirali-s committed Dec 16, 2024
1 parent 0125615 commit 2e6df97
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 7 deletions.
4 changes: 4 additions & 0 deletions Data/Data/Repository/UserRepository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 39 additions & 0 deletions Data/Data/Store/UserStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//

import FirebaseFirestore
import FirebaseAuth

class UserStore: ObservableObject {

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.")
}
}
}
}
32 changes: 25 additions & 7 deletions Splito/UI/Login/EmailLogin/EmailLoginViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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: "",
Expand Down

0 comments on commit 2e6df97

Please sign in to comment.