|
| 1 | +@preconcurrency import FirebaseAuth |
| 2 | +import Observation |
| 3 | + |
| 4 | +protocol EmailPasswordOperationReauthentication { |
| 5 | + var passwordPrompt: PasswordPromptCoordinator { get } |
| 6 | +} |
| 7 | + |
| 8 | +extension EmailPasswordOperationReauthentication { |
| 9 | + func reauthenticate() async throws -> AuthenticationToken { |
| 10 | + guard let user = Auth.auth().currentUser else { |
| 11 | + throw AuthServiceError.reauthenticationRequired("No user currently signed-in") |
| 12 | + } |
| 13 | + |
| 14 | + guard let email = user.email else { |
| 15 | + throw AuthServiceError.invalidCredentials("User does not have an email address") |
| 16 | + } |
| 17 | + |
| 18 | + do { |
| 19 | + let password = try await passwordPrompt.confirmPassword() |
| 20 | + |
| 21 | + let credential = EmailAuthProvider.credential(withEmail: email, password: password) |
| 22 | + try await Auth.auth().currentUser?.reauthenticate(with: credential) |
| 23 | + |
| 24 | + return .firebase("") |
| 25 | + } catch { |
| 26 | + throw AuthServiceError.signInFailed(underlying: error) |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +class EmailPasswordDeleteUserOperation: DeleteUserOperation, |
| 32 | + EmailPasswordOperationReauthentication { |
| 33 | + let passwordPrompt: PasswordPromptCoordinator |
| 34 | + |
| 35 | + init(passwordPrompt: PasswordPromptCoordinator) { |
| 36 | + self.passwordPrompt = passwordPrompt |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +@MainActor |
| 41 | +@Observable |
| 42 | +public final class PasswordPromptCoordinator { |
| 43 | + var isPromptingPassword = false |
| 44 | + private var continuation: CheckedContinuation<String, Error>? |
| 45 | + |
| 46 | + func confirmPassword() async throws -> String { |
| 47 | + return try await withCheckedThrowingContinuation { continuation in |
| 48 | + self.continuation = continuation |
| 49 | + self.isPromptingPassword = true |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + func submit(password: String) { |
| 54 | + continuation?.resume(returning: password) |
| 55 | + cleanup() |
| 56 | + } |
| 57 | + |
| 58 | + func cancel() { |
| 59 | + continuation? |
| 60 | + .resume(throwing: AuthServiceError.reauthenticationRequired("Password entry cancelled")) |
| 61 | + cleanup() |
| 62 | + } |
| 63 | + |
| 64 | + private func cleanup() { |
| 65 | + continuation = nil |
| 66 | + isPromptingPassword = false |
| 67 | + } |
| 68 | +} |
0 commit comments