diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift index 0f54108e84..0e0a6839f0 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift @@ -712,7 +712,7 @@ public extension AuthService { } let task: Task - if isReauthenticating { + if hasPendingEmailLinkReauth() { task = Task { try await self.handleEmailLinkReauthentication(url: url) } } else { guard url != lastSignedInEmailLink else { return } @@ -797,7 +797,7 @@ public extension AuthService { /// ``AuthView/emailLink`` when that screen isn't already showing to handle it itself. An app /// that shows its own screen through `withEmailLinkSignIn(onTap:)` handles links there. internal func presentEmailLinkScreen(for url: URL) { - guard emailLinkSignInEnabled, emailLinkUsesLibraryScreen, !isReauthenticating, + guard emailLinkSignInEnabled, emailLinkUsesLibraryScreen, !hasPendingEmailLinkReauth(), authenticationState != .authenticated, !(isPresented && authView == .emailLink), isEmailSignInLink(url) else { return } @@ -811,12 +811,26 @@ public extension AuthService { /// ``EmailLinkReauthView`` isn't showing, for example after a cold launch. Does nothing for /// other links, or when that view is showing to handle the link itself. internal func finishEmailLinkReauthentication(with url: URL) async throws { - // `auth.currentUser`, not `currentUser`: after a cold launch the link can arrive before the - // auth listener has filled in `currentUser`. - guard isReauthenticating, !isShowingEmailLinkReauth, auth.currentUser != nil else { return } + guard !isShowingEmailLinkReauth, hasPendingEmailLinkReauth() else { return } try await handleSignInLink(url: url) } + /// Forgets a pending email-link reauthentication, so links opened later are handled as + /// sign-in links. Called when ``EmailLinkReauthView`` is cancelled or dismissed. + internal func cancelEmailLinkReauthentication() { + emailLinkReauth = nil + isReauthenticating = false + } + + /// Whether a link the app opens is for email-link reauthentication. Reauthentication left over + /// from a user who is no longer signed in doesn't count, so a sign-in link isn't taken for it. + /// It is kept rather than cleared, in case the user can't be read yet. Reads + /// `auth.currentUser`, which ``currentUser`` may not have caught up with after a cold launch. + private func hasPendingEmailLinkReauth() -> Bool { + guard isReauthenticating, let user = auth.currentUser else { return false } + return !user.isAnonymous + } + private func signInWithEmailLink(email: String, link: String, anonymousUserID: String?) async throws { diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift index f39e1ba808..ed5a4e3392 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift @@ -98,7 +98,10 @@ public struct EmailLinkReauthScreen: View { VStack(spacing: 0) { content(EmailLinkReauthContentState( resendLink: { Task { await sendLink() } }, - cancel: { coordinator.reauthCancelled() }, + cancel: { + authService.cancelEmailLinkReauthentication() + coordinator.reauthCancelled() + }, email: email, linkSent: linkSent, isLoading: isLoading, @@ -113,7 +116,12 @@ public struct EmailLinkReauthScreen: View { } // `AuthPickerContent` leaves reauthentication links to this screen while it shows. .onAppear { authService.isShowingEmailLinkReauth = true } - .onDisappear { authService.isShowingEmailLinkReauth = false } + // Closing the screen abandons reauthentication. After it finishes, there is nothing left to + // forget. + .onDisappear { + authService.isShowingEmailLinkReauth = false + authService.cancelEmailLinkReauthentication() + } .task { await sendLink() } @@ -129,6 +137,12 @@ public struct EmailLinkReauthScreen: View { defer { isLoading = false } do { try await authService.sendEmailSignInLink(email: email, isReauth: true) + // Closed while the email was sending: the send can't be stopped, so forget the + // reauthentication it just stored. + guard authService.isShowingEmailLinkReauth else { + authService.cancelEmailLinkReauthentication() + return + } linkSent = true } catch { report(error) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/ReauthenticationModifier.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/ReauthenticationModifier.swift index f26e699be1..9b0030a653 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/ReauthenticationModifier.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/ReauthenticationModifier.swift @@ -91,7 +91,15 @@ struct ReauthenticationModifier: ViewModifier { } } // Sheet for email link reauthentication - .sheet(isPresented: $coordinator.showingEmailLinkReauth, onDismiss: cancelIfPending) { + // Swiping the sheet away cancels, so the caller waiting on reauthentication isn't left + // hanging. Leaves alone a finished or cancelled reauthentication, and a new request made + // while the sheet was closing. + .sheet(isPresented: $coordinator.showingEmailLinkReauth, onDismiss: { + if case .emailLink = coordinator.reauthContext, + !coordinator.showingEmailLinkReauthAlert { + cancelIfPending() + } + }) { if case let .emailLink(context) = coordinator.reauthContext { EmailLinkReauthScreen(email: context.email, coordinator: coordinator) { ReauthPromptContent(prompt: .emailLink($0)) diff --git a/FirebaseSwiftUI/README.md b/FirebaseSwiftUI/README.md index 2da8e5306d..1ea58b670d 100644 --- a/FirebaseSwiftUI/README.md +++ b/FirebaseSwiftUI/README.md @@ -279,7 +279,7 @@ When a sensitive operation requires reauthentication, the default views automati - **Email/Password**: Present a sheet prompting the user to enter their password before continuing. -- **Email Link**: Show an alert asking to send a verification email, then present a sheet with instructions to check email. The user taps the link in their email to complete reauthentication. `AuthPickerView` also completes it when the link opens the app after the sheet closed, for example after a cold launch. The action that asked for reauthentication isn't resumed then, so the user retries it. +- **Email Link**: Show an alert asking to send a verification email, then present a sheet with instructions to check email. The user taps the link in their email to complete reauthentication. `AuthPickerView` also completes it when the app was closed while the sheet was showing and the link reopens it. The action that asked for reauthentication isn't resumed then, so the user retries it. - **Phone**: Show an alert explaining verification is needed, then present a sheet for SMS code verification. diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift index b90cd4bdaf..59e649c413 100644 --- a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift @@ -261,6 +261,54 @@ struct EmailLinkDeviceTests { try await relaunched.signOut() } + @Test + func cancelledReauthLeavesLaterLinksToSignIn() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + try await service.handleSignInLink(url: fetchEmailSignInLinkFromEmulator(email: email)) + try await waitForStateChange { + service.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame + } + + try await service.sendEmailSignInLink(email: email, isReauth: true) + #expect(service.isReauthenticating) + // What cancelling or dismissing `EmailLinkReauthView` does. + service.cancelEmailLinkReauthentication() + #expect(!service.isReauthenticating) + + // A relaunch doesn't bring the cancelled reauthentication back. + let relaunched = try await makeService(clearingEmulator: false) + #expect(!relaunched.isReauthenticating) + try await relaunched.signOut() + } + + @Test + func signInLinkIsNotTakenForReauthWithoutSignedInUser() async throws { + let service = try await makeService() + try service.auth.signOut() + // Reauthentication left over in storage, for example from a session that has since ended + // without `signOut()`. + try await service.sendEmailSignInLink(email: createEmail(), isReauth: true) + #expect(service.isReauthenticating) + + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + + service.presentEmailLinkScreen(for: link) + #expect(service.incomingEmailLink == link) + // Nothing to finish, so the picker leaves the link to the email-link screen. + try await service.finishEmailLinkReauthentication(with: link) + #expect(service.currentUser == nil) + + try await service.handleSignInLink(url: link) + try await waitForStateChange { + service.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame + } + try await service.signOut() + } + @Test func openedLinkPresentsEmailLinkScreen() throws { configureFirebaseIfNeeded()