Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -712,7 +712,7 @@ public extension AuthService {
}

let task: Task<Void, Error>
if isReauthenticating {
if hasPendingEmailLinkReauth() {
task = Task { try await self.handleEmailLinkReauthentication(url: url) }
} else {
guard url != lastSignedInEmailLink else { return }
Expand Down Expand Up @@ -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(),
Comment thread
demolaf marked this conversation as resolved.
Resolved
authenticationState != .authenticated,
!(isPresented && authView == .emailLink),
isEmailSignInLink(url) else { return }
Expand All @@ -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 }
Comment thread
demolaf marked this conversation as resolved.
Resolved
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
}
Comment thread
demolaf marked this conversation as resolved.
Resolved

private func signInWithEmailLink(email: String,
link: String,
anonymousUserID: String?) async throws {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,10 @@ public struct EmailLinkReauthScreen<Content: View>: View {
VStack(spacing: 0) {
content(EmailLinkReauthContentState(
resendLink: { Task { await sendLink() } },
cancel: { coordinator.reauthCancelled() },
cancel: {
authService.cancelEmailLinkReauthentication()
coordinator.reauthCancelled()
},
email: email,
linkSent: linkSent,
isLoading: isLoading,
Expand All @@ -113,7 +116,12 @@ public struct EmailLinkReauthScreen<Content: View>: 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()
}
Expand All @@ -129,6 +137,12 @@ public struct EmailLinkReauthScreen<Content: View>: 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion FirebaseSwiftUI/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading