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 @@ -250,6 +250,8 @@ public final class AuthService {
/// A sign-in link the app opened while ``EmailLinkScreen`` wasn't showing, handed to it
/// when it appears.
var incomingEmailLink: URL?
/// Whether ``EmailLinkReauthScreen`` is showing, so it handles reauthentication links itself.
@ObservationIgnored var isShowingEmailLinkReauth = false
public var legacySignInRecovery: LegacySignInRecoveryContext?
public var suggestedEmailAddress: String?
/// How many in-place email forms (an ``EmailAuthScreen`` without a fixed flow) exist on the
Expand Down Expand Up @@ -702,19 +704,20 @@ public extension AuthService {
/// set. A link that is already being handled waits for that attempt and gets its outcome, and
/// a link that already signed in is ignored until sign-out.
func handleSignInLink(url: URL) async throws {
if isReauthenticating {
try await handleEmailLinkReauthentication(url: url)
return
}

// A second caller with the same link waits for the first and gets the same outcome.
// A second caller with the same link waits for the first and gets the same outcome,
// whether it signs in or reauthenticates.
if let inFlight = emailLinkInFlight, inFlight.url == url {
try await inFlight.task.value
return
}
guard url != lastSignedInEmailLink else { return }

let task = Task { try await self.signInWithOpenedLink(url: url) }
let task: Task<Void, Error>
if isReauthenticating {
task = Task { try await self.handleEmailLinkReauthentication(url: url) }
} else {
guard url != lastSignedInEmailLink else { return }
task = Task { try await self.signInWithOpenedLink(url: url) }
}
emailLinkInFlight = (url, task)
defer {
if emailLinkInFlight?.url == url {
Expand Down Expand Up @@ -804,6 +807,16 @@ public extension AuthService {
navigator.push(.emailLink)
}

/// Finishes email-link reauthentication with a link the app opened while
/// ``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 }
try await handleSignInLink(url: url)
}

private func signInWithEmailLink(email: String,
link: String,
anonymousUserID: String?) async throws {
Expand Down Expand Up @@ -849,6 +862,8 @@ public extension AuthService {
}
emailLinkReauth = nil
isReauthenticating = false
// The same link can be delivered again; don't take it for a sign-in link then.
lastSignedInEmailLink = url
}

/// The continue URL of the sign-in link inside a URL the app opened. Read before
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,12 @@ public struct AuthPickerContent<
@Bindable var authService = authService
content()
// A sign-in link opened while the email-link screen isn't showing, for example on
// another device or after a cold launch, opens that screen to finish signing in.
.onOpenURL { authService.presentEmailLinkScreen(for: $0) }
// another device or after a cold launch, opens that screen to finish signing in. A
// reauthentication link opened while its screen isn't showing finishes it here.
.onOpenURL { url in
authService.presentEmailLinkScreen(for: url)
finishEmailLinkReauthentication(with: url)
}
// Reopening the sheet starts from the first screen, not a half-finished pushed one.
.sheet(isPresented: $authService.isPresented, onDismiss: {
authService.navigator.clear()
Expand Down Expand Up @@ -194,6 +198,18 @@ public struct AuthPickerContent<
)
}

private func finishEmailLinkReauthentication(with url: URL) {
Task { @MainActor in
do {
try await authService.finishEmailLinkReauthentication(with: url)
} catch {
// The sheet holds the error alert, and may be closed after a cold launch.
authService.isPresented = true
reportError(error)
}
}
}

/// Closure for reporting errors from child views
private func reportError(_ error: Error) {
Task { @MainActor in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ public struct EmailLinkReauthScreen<Content: View>: View {
guard authService.isEmailSignInLink(url) else { return }
handleReauthURL(url)
}
// `AuthPickerContent` leaves reauthentication links to this screen while it shows.
.onAppear { authService.isShowingEmailLinkReauth = true }
.onDisappear { authService.isShowingEmailLinkReauth = false }
.task {
await sendLink()
}
Expand All @@ -137,6 +140,8 @@ public struct EmailLinkReauthScreen<Content: View>: View {
Task {
do {
try await authService.handleSignInLink(url: url)
// The URL wasn't a sign-in link, so reauthentication isn't finished.
guard !authService.isReauthenticating else { return }
coordinator.reauthCompleted()
} catch let AuthServiceError.multiFactorReauthenticationRequired(mfaRequired) {
self.mfaRequired = mfaRequired
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.
- **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.

- **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 @@ -21,10 +21,21 @@ import Testing
@Suite(.serialized)
@MainActor
struct EmailLinkDeviceTests {
init() {
// Reauthentication state persists in `UserDefaults`; don't let a failed test leak it.
UserDefaults.standard.removeObject(forKey: "is-reauthenticating")
UserDefaults.standard.removeObject(forKey: "email-link-reauth")
}

private func makeService(continueURL: String = "https://flutterfire-e2e-tests.firebaseapp.com",
forceSameDevice: Bool = false) async throws -> AuthService {
forceSameDevice: Bool = false,
clearingEmulator: Bool = true) async throws -> AuthService {
configureFirebaseIfNeeded()
try await clearAuthEmulatorState()
if clearingEmulator {
try await clearAuthEmulatorState()
} else {
try await isEmulatorRunning()
}
let settings = makeEmailLinkActionCodeSettings()
settings.url = URL(string: continueURL)
return AuthService(
Expand Down Expand Up @@ -205,6 +216,51 @@ struct EmailLinkDeviceTests {
#expect(service.pendingEmailLink == nil)
}

@Test
func reauthLinkOpenedAfterColdLaunchFinishesReauthentication() async throws {
let service = try await makeService()
let email = createEmail()
try await service.sendEmailSignInLink(email: email)
let signInLink = try await fetchEmailSignInLinkFromEmulator(email: email)
try await service.handleSignInLink(url: signInLink)
try await waitForStateChange {
service.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame
}

try await service.sendEmailSignInLink(email: email, isReauth: true)
var reauthLink = signInLink
try await waitForStateChange(timeout: 15) {
reauthLink != signInLink
} refresh: {
reauthLink = try await fetchEmailSignInLinkFromEmulator(email: email)
}

// While `EmailLinkReauthView` shows, its own handler takes the link.
service.isShowingEmailLinkReauth = true
try await service.finishEmailLinkReauthentication(with: reauthLink)
#expect(service.isReauthenticating)
service.isShowingEmailLinkReauth = false

// A cold launch starts a new service with the reauthentication state kept in storage. The
// link can arrive before its auth listener has filled in `currentUser`, so don't wait for it.
let relaunched = try await makeService(clearingEmulator: false)
#expect(relaunched.isReauthenticating)

// `AuthPickerContent` may pass the same link more than once.
let link = reauthLink
let first = Task { try await relaunched.finishEmailLinkReauthentication(with: link) }
let second = Task { try await relaunched.finishEmailLinkReauthentication(with: link) }
try await first.value
try await second.value

#expect(!relaunched.isReauthenticating)

// Delivered again after reauthentication finished, the link isn't taken for a sign-in link.
try await relaunched.handleSignInLink(url: link)
#expect(relaunched.pendingEmailLink == nil)
try await relaunched.signOut()
}

@Test
func openedLinkPresentsEmailLinkScreen() throws {
configureFirebaseIfNeeded()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ func createEmail() -> String {

@MainActor
func waitForStateChange(timeout: TimeInterval = 10.0,
condition: @escaping () -> Bool) async throws {
condition: @escaping () -> Bool,
refresh: () async throws -> Void = {}) async throws {
let startTime = Date()

while !condition() {
Expand All @@ -75,6 +76,7 @@ func waitForStateChange(timeout: TimeInterval = 10.0,
}

try await Task.sleep(nanoseconds: 50_000_000) // 50ms
try await refresh()
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,24 @@ func createEmail() -> String {
return pasteMenuItem
}

/// How long a paste has to show up in a field. On a busy CI simulator the pasted text can
/// appear several seconds after the Paste tap.
private let pasteTimeout: TimeInterval = 10

@MainActor private func typeIntoField(_ field: XCUIElement,
text: String,
app: XCUIApplication) throws {
UIPasteboard.general.string = text
let pasteMenuItem = try showPasteMenu(for: field, text: text, app: app)
pasteMenuItem.tap()

let success = waitForFieldValue(field, expectedText: text, timeout: 3)
UIPasteboard.general.string = nil
defer { UIPasteboard.general.string = nil }

var success = false
for attempt in 0 ..< 2 {
// Paste again only into a field without the text, so a late first paste isn't doubled.
if attempt > 0, let value = field.value as? String, value.contains(text) { break }
try showPasteMenu(for: field, text: text, app: app).tap()
success = waitForFieldValue(field, expectedText: text, timeout: pasteTimeout)
if success { break }
}

guard success else {
throw NSError(
Expand All @@ -122,7 +131,7 @@ func createEmail() -> String {

// Poll until the value changes rather than relying on a fixed sleep.
// Secure fields show bullet characters so we can only detect a change, not the exact value.
let deadline = Date().addingTimeInterval(3.0)
let deadline = Date().addingTimeInterval(pasteTimeout)
var pasted = false
while Date() < deadline {
if (field.value as? String) != originalValue {
Expand Down
Loading