diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift index 548bf37363..b866b6ea06 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift @@ -206,12 +206,21 @@ public final class AuthService { @ObservationIgnored @AppStorage("is-email-link") private var isEmailLinkSignIn: Bool = false // Storage for email link reauthentication (separate from sign-in) @ObservationIgnored @AppStorage("email-link-reauth") private var emailLinkReauth: String? - @ObservationIgnored @AppStorage("is-reauthenticating") private var isReauthenticating: Bool = - false + @ObservationIgnored @AppStorage("is-reauthenticating") private(set) var isReauthenticating: + Bool = false + /// Identifies the last sign-in link this device sent, written on the link as `ui_sid`. + @ObservationIgnored @AppStorage("email-link-session-id") private var emailLinkSessionID: String? private var currentMFAResolver: MultiFactorResolver? private var listenerManager: AuthListenerManager? private var emailLinkSignInCallback: (() -> Void)? + /// Whether the email-link button pushes the library's ``AuthView/emailLink`` screen rather + /// than running an app's own `onTap`. + private var emailLinkUsesLibraryScreen = false + /// The sign-in link being handled, and the last one that signed in, so a link delivered to + /// several `onOpenURL` handlers is only used once. + @ObservationIgnored private var emailLinkInFlight: (url: URL, task: Task)? + @ObservationIgnored private var lastSignedInEmailLink: URL? private var providers: [AuthProviderUI] = [] private let emailLinkSignInMethod = "emailLink" @@ -232,6 +241,15 @@ public final class AuthService { /// library. public private(set) var allowNewEmailAccounts = true public var emailLinkSignInEnabled = false + /// Whether a sign-in link only works on the device that requested it. Set with + /// ``withEmailLinkSignIn(forceSameDevice:)``. + public private(set) var emailLinkForceSameDevice = false + /// A sign-in link opened on a device that didn't request it, waiting for + /// ``confirmEmailLinkSignIn(email:)``. + public private(set) var pendingEmailLink: URL? + /// A sign-in link the app opened while ``EmailLinkScreen`` wasn't showing, handed to it + /// when it appears. + var incomingEmailLink: URL? public var legacySignInRecovery: LegacySignInRecoveryContext? public var suggestedEmailAddress: String? /// How many in-place email forms (an ``EmailAuthScreen`` without a fixed flow) exist on the @@ -323,6 +341,9 @@ public final class AuthService { try auth.signOut() // Cannot wait for auth listener to change, feedback needs to be immediate currentUser = nil + clearEmailLinkHandoff() + // A link that signed in before is expired now; let it fail again rather than do nothing. + lastSignedInEmailLink = nil // Clear email link sign-in flag isEmailLinkSignIn = false // Clear email link reauth state @@ -621,17 +642,31 @@ public extension AuthService { // MARK: - Email Link Sign In public extension AuthService { - /// Enable email link sign-in with default behavior (navigates to email link view) - func withEmailLinkSignIn() -> AuthService { - return withEmailLinkSignIn { [weak self] in + /// Enables email-link sign-in. Its button pushes ``AuthView/emailLink``. + /// + /// - Parameter forceSameDevice: Whether a link only works on the device that requested it. + /// When `false`, a link opened on another device asks the user to confirm their email + /// first. Defaults to `false`. + func withEmailLinkSignIn(forceSameDevice: Bool = false) -> AuthService { + _ = withEmailLinkSignIn(forceSameDevice: forceSameDevice) { [weak self] in self?.navigator.push(.emailLink) } + emailLinkUsesLibraryScreen = true + return self } - /// Enable email link sign-in with custom callback - func withEmailLinkSignIn(onTap: @escaping () -> Void) -> AuthService { + /// Enables email-link sign-in with a custom action for its button. + /// + /// - Parameters: + /// - forceSameDevice: Whether a link only works on the device that requested it. Defaults + /// to `false`. + /// - onTap: Runs when the email-link button is tapped. + func withEmailLinkSignIn(forceSameDevice: Bool = false, + onTap: @escaping () -> Void) -> AuthService { emailLinkSignInEnabled = true + emailLinkForceSameDevice = forceSameDevice emailLinkSignInCallback = onTap + emailLinkUsesLibraryScreen = false return self } @@ -640,7 +675,8 @@ public extension AuthService { /// - email: Email address to send link to /// - isReauth: Whether this is for reauthentication (default: false) func sendEmailSignInLink(email: String, isReauth: Bool = false) async throws { - let actionCodeSettings = try updateActionCodeSettings() + let sessionID = isReauth ? nil : String(Int.random(in: 0 ... 999_999_999)) + let actionCodeSettings = try updateActionCodeSettings(sessionID: sessionID) try await auth.sendSignInLink( toEmail: email, actionCodeSettings: actionCodeSettings @@ -650,104 +686,202 @@ public extension AuthService { if isReauth { emailLinkReauth = email isReauthenticating = true + } else { + emailLink = email + emailLinkSessionID = sessionID + pendingEmailLink = nil } } + /// Signs in with a sign-in link the app opened, or reauthenticates when + /// ``sendEmailSignInLink(email:isReauth:)`` sent it for reauthentication. + /// + /// A link opened on a device that didn't request it throws + /// ``AuthServiceError/invalidEmailLink(_:)`` as before, and also sets ``pendingEmailLink`` for + /// ``confirmEmailLinkSignIn(email:)`` unless ``withEmailLinkSignIn(forceSameDevice:)`` is + /// 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 { - do { - // Check which flow we're in based on the flag - let email: String - let isReauth = isReauthenticating - - if isReauth { - guard let reauthEmail = emailLinkReauth else { - throw AuthServiceError - .invalidEmailLink("Email address is missing for reauthentication") - } - email = reauthEmail - } else { - guard let signInEmail = emailLink else { - throw AuthServiceError - .invalidEmailLink("email address is missing from app storage. Is this the same device?") - } - email = signInEmail + if isReauthenticating { + try await handleEmailLinkReauthentication(url: url) + return + } + + // A second caller with the same link waits for the first and gets the same outcome. + 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) } + emailLinkInFlight = (url, task) + defer { + if emailLinkInFlight?.url == url { + emailLinkInFlight = nil } + } + try await task.value + } - let urlString = url.absoluteString + private func signInWithOpenedLink(url: URL) async throws { + let link = try Self.emailSignInLink(from: url) + guard auth.isSignIn(withEmailLink: link) else { return } - guard let originalLink = CommonUtils.getQueryParamValue(from: urlString, paramName: "link") - else { - throw AuthServiceError - .invalidEmailLink("'link' parameter is missing from the email link URL") + guard let continueURL = try Self.continueURL(from: url) else { + throw AuthServiceError + .invalidEmailLink("`continueUrl` parameter is missing from the email link URL") + } + let parameter = { CommonUtils.getQueryParamValue(from: continueURL, paramName: $0) } + + // A link without `ui_sid`, sent before it existed, counts as this device's only when this + // device hasn't sent a link since. + let linkSessionID = parameter("ui_sid") + guard let email = emailLink, linkSessionID == emailLinkSessionID else { + if parameter("ui_sd") == "1" { + throw AuthServiceError.invalidEmailLink(string.emailLinkDifferentDeviceMessage) } + pendingEmailLink = url + throw AuthServiceError + .invalidEmailLink("email address is missing from app storage. Is this the same device?") + } - guard let link = originalLink.removingPercentEncoding else { - throw AuthServiceError - .invalidEmailLink("Failed to decode Link URL") + try await signInWithEmailLink(email: email, link: link, anonymousUserID: parameter("ui_auid")) + lastSignedInEmailLink = url + } + + /// Finishes signing in with ``pendingEmailLink`` once the user confirms the email address the + /// link was sent to. Never upgrades an anonymous user, since that user is on another device. + func confirmEmailLinkSignIn(email: String) async throws { + guard let url = pendingEmailLink else { + throw AuthServiceError.invalidEmailLink("No sign-in link is waiting for confirmation") + } + let link = try Self.emailSignInLink(from: url) + do { + try await signInWithEmailLink(email: email, link: link, anonymousUserID: nil) + lastSignedInEmailLink = url + } catch { + // A used or expired link can't succeed with any email, so stop asking for one. + let code = AuthErrorCode(rawValue: (error as NSError).code) + if code == .invalidActionCode || code == .expiredActionCode { + pendingEmailLink = nil } + throw error + } + } - if auth.isSignIn(withEmailLink: link) { - let credential = EmailAuthProvider.credential(withEmail: email, link: link) + /// Drops ``pendingEmailLink`` so the email-link screen offers to send a new link instead of + /// asking to confirm the email. + func cancelEmailLinkConfirmation() { + pendingEmailLink = nil + } - if isReauth { - // Reauthentication flow - try await reauthenticate(with: credential) - // Clean up reauth state - emailLinkReauth = nil - isReauthenticating = false - } else { - // Sign-in flow - guard let continueUrl = CommonUtils.getQueryParamValue( - from: link, - paramName: "continueUrl" - ) - else { - throw AuthServiceError - .invalidEmailLink("`continueUrl` parameter is missing from the email link URL") - } + /// Forgets links waiting for the email-link screen, when the sheet closes or the user signs + /// out. + internal func clearEmailLinkHandoff() { + pendingEmailLink = nil + incomingEmailLink = nil + } - let anonymousUserID = CommonUtils.getQueryParamValue( - from: continueUrl, - paramName: "ui_auid" - ) - if shouldHandleAnonymousUpgrade, anonymousUserID == currentUser?.uid { - _ = try await handleAutoUpgradeAnonymousUser(credentials: credential) - } else { - _ = try await auth.signIn(withEmail: email, link: link) - } - updateAuthenticationState() - // Track that user signed in with email link - isEmailLinkSignIn = true - emailLink = nil - } + /// Whether a URL the app opened carries a Firebase email sign-in link, so screens can leave + /// the app's other deep links alone. + internal func isEmailSignInLink(_ url: URL) -> Bool { + guard let link = try? Self.emailSignInLink(from: url) else { return false } + return auth.isSignIn(withEmailLink: link) + } + + /// Hands a sign-in link the app opened to ``EmailLinkScreen``, presenting the sheet and pushing + /// ``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, + authenticationState != .authenticated, + !(isPresented && authView == .emailLink), + isEmailSignInLink(url) else { return } + + incomingEmailLink = url + isPresented = true + navigator.push(.emailLink) + } + + private func signInWithEmailLink(email: String, + link: String, + anonymousUserID: String?) async throws { + let credential = EmailAuthProvider.credential(withEmail: email, link: link) + do { + if let anonymousUserID, shouldHandleAnonymousUpgrade, + anonymousUserID == currentUser?.uid { + _ = try await handleAutoUpgradeAnonymousUser(credentials: credential) + } else { + _ = try await auth.signIn(withEmail: email, link: link) } } catch { - // Determine which email to use for error handling - let email = isReauthenticating ? emailLinkReauth : emailLink - let link = url.absoluteString + // Possible conflicts from auth.signIn(withEmail:link:): + // - accountExistsWithDifferentCredential: account exists with different provider + // - credentialAlreadyInUse: credential is already linked to another account + try handleErrorWithConflictCheck(error: error, credential: credential) + } + updateAuthenticationState() + // Track that user signed in with email link + isEmailLinkSignIn = true + emailLink = nil + emailLinkSessionID = nil + pendingEmailLink = nil + } - guard let email = email else { - throw AuthServiceError - .invalidEmailLink("email address is missing from app storage") - } - let credential = EmailAuthProvider.credential(withEmail: email, link: link) - - // Only handle conflicts for sign-in flow, not reauth - if !isReauthenticating { - // Possible conflicts from auth.signIn(withEmail:link:): - // - accountExistsWithDifferentCredential: account exists with different provider - // - credentialAlreadyInUse: credential is already linked to another account - try handleErrorWithConflictCheck(error: error, credential: credential) - } else { - // For reauth, just rethrow. The link is consumed even when a second factor is still - // required, so clean up reauth state in that case. - if case AuthServiceError.multiFactorReauthenticationRequired = error { - emailLinkReauth = nil - isReauthenticating = false - } - throw error + private func handleEmailLinkReauthentication(url: URL) async throws { + guard let email = emailLinkReauth else { + throw AuthServiceError.invalidEmailLink("Email address is missing for reauthentication") + } + let link = try Self.emailSignInLink(from: url) + guard auth.isSignIn(withEmailLink: link) else { return } + + do { + try await reauthenticate(with: EmailAuthProvider.credential(withEmail: email, link: link)) + } catch { + // The link is consumed even when a second factor is still required, so clean up + // reauth state in that case. + if case AuthServiceError.multiFactorReauthenticationRequired = error { + emailLinkReauth = nil + isReauthenticating = false } + throw error + } + emailLinkReauth = nil + isReauthenticating = false + } + + /// The continue URL of the sign-in link inside a URL the app opened. Read before + /// ``emailSignInLink(from:)`` decodes the link a second time, which would split the continue + /// URL's own query items off onto the link. + private static func continueURL(from url: URL) throws -> String? { + guard let originalLink = CommonUtils.getQueryParamValue( + from: url.absoluteString, + paramName: "link" + ) else { + throw AuthServiceError + .invalidEmailLink("'link' parameter is missing from the email link URL") } + return CommonUtils.getQueryParamValue(from: originalLink, paramName: "continueUrl") + ?? CommonUtils.getQueryParamValue( + from: originalLink.removingPercentEncoding ?? originalLink, + paramName: "continueUrl" + ) + } + + /// The Firebase sign-in link inside the `link` query parameter of a URL the app opened. + private static func emailSignInLink(from url: URL) throws -> String { + guard let originalLink = CommonUtils.getQueryParamValue( + from: url.absoluteString, + paramName: "link" + ) else { + throw AuthServiceError + .invalidEmailLink("'link' parameter is missing from the email link URL") + } + guard let link = originalLink.removingPercentEncoding else { + throw AuthServiceError.invalidEmailLink("Failed to decode Link URL") + } + return link } } @@ -1141,7 +1275,10 @@ private extension AuthService { return actionCodeSettings } - private func updateActionCodeSettings() throws -> ActionCodeSettings { + /// The continue-URL query items the library writes on email sign-in links. + static let emailLinkQueryItemNames: Set = ["ui_auid", "ui_sid", "ui_sd"] + + private func updateActionCodeSettings(sessionID: String?) throws -> ActionCodeSettings { let actionCodeSettings = try safeActionCodeSettings() guard var urlComponents = URLComponents(string: actionCodeSettings.url!.absoluteString) else { throw AuthServiceError @@ -1150,7 +1287,11 @@ private extension AuthService { ) } - var queryItems: [URLQueryItem] = [] + // Keep the app's own query items. The configured settings object is reused for every + // link, so drop the items an earlier link added before adding this link's. + var queryItems = (urlComponents.queryItems ?? []).filter { + !Self.emailLinkQueryItemNames.contains($0.name) + } if shouldHandleAnonymousUpgrade { if let currentUser = currentUser { @@ -1160,7 +1301,13 @@ private extension AuthService { } } - urlComponents.queryItems = queryItems + // Lets the device that opens the link tell whether it sent it, as the UIKit library did. + if let sessionID { + queryItems.append(URLQueryItem(name: "ui_sid", value: sessionID)) + queryItems.append(URLQueryItem(name: "ui_sd", value: emailLinkForceSameDevice ? "1" : "0")) + } + + urlComponents.queryItems = queryItems.isEmpty ? nil : queryItems if let finalURL = urlComponents.url { actionCodeSettings.url = finalURL } diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Strings/Localizable.xcstrings b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Strings/Localizable.xcstrings index b8b9e159d7..c63c11a519 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Strings/Localizable.xcstrings +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Strings/Localizable.xcstrings @@ -8862,6 +8862,18 @@ } } }, + "ConfirmEmailLinkMessage" : { + "comment" : "Shown when an email sign-in link is opened on a device that didn't request it.", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "You opened this sign-in link on a different device or browser. Enter the email address it was sent to." + } + } + } + }, "ConfirmPasswordInputLabel" : { "comment" : "Input label for confirming password when signing up", "extractionState" : "manual", @@ -12466,6 +12478,18 @@ } } }, + "EmailLinkDifferentDeviceMessage" : { + "comment" : "Error when an email sign-in link that must stay on one device is opened on another.", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Open this sign-in link on the device where you requested it." + } + } + } + }, "EmailsDontMatch" : { "comment" : "Error message displayed when after re-authorization current user's email and re-authorized user's email doesn't match. Use short/abbreviated translation for 'email' which is less than 15 chars.", "extractionState" : "manual", diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Utils/StringUtils.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Utils/StringUtils.swift index 3975619d98..5e86324063 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Utils/StringUtils.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Utils/StringUtils.swift @@ -1079,9 +1079,31 @@ public class StringUtils { return String(format: localizedString(for: "Email: %@"), email) } + /// Confirm email title + /// found in: + /// - DefaultEmailLinkContent + public var confirmEmailTitle: String { + return localizedString(for: "ConfirmEmail") + } + + /// Message asking to confirm the email address of a sign-in link opened on another device + /// found in: + /// - DefaultEmailLinkContent + public var confirmEmailLinkMessage: String { + return localizedString(for: "ConfirmEmailLinkMessage") + } + + /// Error for a same-device sign-in link opened on another device + /// found in: + /// - AuthService + public var emailLinkDifferentDeviceMessage: String { + return localizedString(for: "EmailLinkDifferentDeviceMessage") + } + /// Confirm button label /// found in: /// - EmailReauthView + /// - DefaultEmailLinkContent public var confirmButtonLabel: String { return localizedString(for: "Confirm") } diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift index b05b732c30..c5b06fa37d 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift @@ -58,8 +58,14 @@ public struct AuthPickerContent< public var body: some View { @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) } // Reopening the sheet starts from the first screen, not a half-finished pushed one. - .sheet(isPresented: $authService.isPresented, onDismiss: authService.navigator.clear) { + .sheet(isPresented: $authService.isPresented, onDismiss: { + authService.navigator.clear() + authService.clearEmailLinkHandoff() + }) { @Bindable var navigator = authService.navigator NavigationStack(path: $navigator.routes) { root diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift index da5046691f..1af0860845 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift @@ -27,9 +27,17 @@ public struct DefaultEmailLinkContent: View { public var body: some View { VStack(spacing: 24) { + if state.needsEmailConfirmation { + Text(authService.string.confirmEmailLinkMessage) + .authCustomFont(.body) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityIdentifier("email-link-confirm-message") + } AuthTextField( text: state.email, - label: authService.string.signInLinkEmailFieldLabel, + label: state.needsEmailConfirmation + ? authService.string.emailFieldLabel + : authService.string.signInLinkEmailFieldLabel, prompt: authService.string.emailInputLabel, keyboardType: .emailAddress, contentType: .emailAddress, @@ -41,18 +49,40 @@ public struct DefaultEmailLinkContent: View { } ) .accessibilityIdentifier("email-link-email-field") - Button(action: state.sendSignInLink) { - Text(authService.string.sendEmailLinkButtonLabel) - .padding(.vertical, 8) - .frame(maxWidth: .infinity) + Button { + if state.needsEmailConfirmation { + state.confirmEmail() + } else { + state.sendSignInLink() + } + } label: { + Text( + state.needsEmailConfirmation + ? authService.string.confirmButtonLabel + : authService.string.sendEmailLinkButtonLabel + ) + .padding(.vertical, 8) + .frame(maxWidth: .infinity) } .authCTAButtonStyle() + .accessibilityIdentifier( + state.needsEmailConfirmation ? "email-link-confirm-button" : "email-link-send-button" + ) .disabled(!state.isValid || state.isLoading) .padding([.top, .bottom], 8) .frame(maxWidth: .infinity) + if state.needsEmailConfirmation { + Button(authService.string.cancelButtonLabel, action: state.cancelConfirmation) + .disabled(state.isLoading) + .accessibilityIdentifier("email-link-cancel-confirmation-button") + } } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) - .navigationTitle(authService.string.signInWithEmailLinkViewTitle) + .navigationTitle( + state.needsEmailConfirmation + ? authService.string.confirmEmailTitle + : authService.string.signInWithEmailLinkViewTitle + ) .safeAreaPadding() .errorMessageAlert( state.errorMessage, diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift index e005200aa0..4b2c68f865 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift @@ -107,6 +107,8 @@ public struct EmailLinkReauthScreen: View { )) } .onOpenURL { url in + // The app's other deep links reach this handler too; they aren't errors here. + guard authService.isEmailSignInLink(url) else { return } handleReauthURL(url) } .task { diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift index 6fb7ca0d79..d0c55ff972 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift @@ -28,6 +28,20 @@ public struct EmailLinkContentState { /// Clears ``didSend``. public let dismissAlert: @MainActor () -> Void + /// Signs in with the link waiting for confirmation, using ``email`` as the address it was + /// sent to. Does nothing unless ``needsEmailConfirmation`` and ``isValid`` are `true` and + /// ``isLoading`` is `false`. + public let confirmEmail: @MainActor () -> Void + + /// Drops the link waiting for confirmation, so ``needsEmailConfirmation`` turns `false` and + /// the user can send a new link. + public let cancelConfirmation: @MainActor () -> Void + + /// Whether a sign-in link was opened on a device that didn't request it, so the user must + /// enter the email address it was sent to and call ``confirmEmail``. Turned off with + /// ``AuthService/withEmailLinkSignIn(forceSameDevice:)``. + public let needsEmailConfirmation: Bool + /// Whether a sign-in link was sent and ``dismissAlert`` hasn't been called since. public let didSend: Bool @@ -51,6 +65,9 @@ public struct EmailLinkContentState { public init(email: Binding = .constant(""), sendSignInLink: @escaping @MainActor () -> Void = {}, dismissAlert: @escaping @MainActor () -> Void = {}, + confirmEmail: @escaping @MainActor () -> Void = {}, + cancelConfirmation: @escaping @MainActor () -> Void = {}, + needsEmailConfirmation: Bool = false, didSend: Bool = false, isValid: Bool = false, isLoading: Bool = false, @@ -59,6 +76,9 @@ public struct EmailLinkContentState { self.email = email self.sendSignInLink = sendSignInLink self.dismissAlert = dismissAlert + self.confirmEmail = confirmEmail + self.cancelConfirmation = cancelConfirmation + self.needsEmailConfirmation = needsEmailConfirmation self.didSend = didSend self.isValid = isValid self.isLoading = isLoading @@ -69,8 +89,9 @@ public struct EmailLinkContentState { /// The email-link screen, with its content drawn by you. /// -/// The screen sends the link, signs in when the app opens it, and routes account conflicts and -/// errors. Your content only draws the UI from the ``EmailLinkContentState`` it receives. Wrap +/// The screen sends the link, signs in when the app opens it, asks for the email address when +/// the link was opened on another device, and routes account conflicts and errors. Your content +/// only draws the UI from the ``EmailLinkContentState`` it receives. Wrap /// ``DefaultEmailLinkContent`` to keep the stock markup. /// /// Example: @@ -116,6 +137,9 @@ public struct EmailLinkScreen: View { email: $email, sendSignInLink: sendSignInLink, dismissAlert: { didSend = false }, + confirmEmail: confirmEmail, + cancelConfirmation: { authService.cancelEmailLinkConfirmation() }, + needsEmailConfirmation: authService.pendingEmailLink != nil, didSend: didSend, isValid: isValid, isLoading: isLoading, @@ -125,32 +149,24 @@ public struct EmailLinkScreen: View { } .onChange(of: email) { errorMessage = nil } .onOpenURL { url in - // A sign-in link is one-time, so ignore another while one is being handled. - guard !isHandlingLink else { return } - isHandlingLink = true - errorMessage = nil - Task { - defer { isHandlingLink = false } - do { - try await authService.handleSignInLink(url: url) - } catch { - if case let AuthServiceError.accountConflict(ctx) = error, - let onConflict = accountConflictHandler { - onConflict(ctx) - return - } - - if shouldShowErrorAlert(for: error) { - errorMessage = authService.string.localizedErrorMessage(for: error) - } - } - } + // The app's other deep links reach this handler too; they aren't errors here. + guard authService.isEmailSignInLink(url) else { return } + handleLink(url) { try await authService.handleSignInLink(url: url) } + } + // A link the app opened before this screen was showing. + .onChange(of: authService.incomingEmailLink, initial: true) { _, url in + guard let url else { return } + authService.incomingEmailLink = nil + handleLink(url) { try await authService.handleSignInLink(url: url) } } .onAppear { if let suggestedEmailAddress = authService.suggestedEmailAddress { email = suggestedEmailAddress } } + // Leaving the screen abandons the link waiting for confirmation, so coming back offers to + // send a new one. + .onDisappear { authService.cancelEmailLinkConfirmation() } .onChange(of: authService.suggestedEmailAddress) { _, suggestedEmailAddress in if let suggestedEmailAddress { email = suggestedEmailAddress @@ -166,6 +182,41 @@ public struct EmailLinkScreen: View { isWorking || isHandlingLink || authService.authenticationState == .authenticating } + private func confirmEmail() { + guard authService.pendingEmailLink != nil, isValid, !isLoading else { return } + let email = self.email + handleLink(nil) { try await authService.confirmEmailLinkSignIn(email: email) } + } + + private func handleLink(_ url: URL?, + _ attempt: @escaping @MainActor () async throws -> Void) { + // A sign-in link is one-time, so ignore another while one is being handled. + guard !isHandlingLink else { return } + isHandlingLink = true + errorMessage = nil + Task { + defer { isHandlingLink = false } + do { + try await attempt() + } catch { + if case let AuthServiceError.accountConflict(ctx) = error, + let onConflict = accountConflictHandler { + onConflict(ctx) + return + } + // This link was opened on another device; the content asks for the email instead. + if case AuthServiceError.invalidEmailLink = error, let url, + authService.pendingEmailLink == url { + return + } + + if shouldShowErrorAlert(for: error) { + errorMessage = authService.string.localizedErrorMessage(for: error) + } + } + } + } + private func sendSignInLink() { guard isValid, !isLoading else { return } let email = self.email @@ -176,7 +227,6 @@ public struct EmailLinkScreen: View { do { try await authService.sendEmailSignInLink(email: email) didSend = true - authService.emailLink = email } catch { if shouldShowErrorAlert(for: error) { errorMessage = authService.string.localizedErrorMessage(for: error) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Tests/FirebaseAuthSwiftUITests/ContentStateDefaultsTests.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Tests/FirebaseAuthSwiftUITests/ContentStateDefaultsTests.swift index 81d661fdcd..1c663fbe0d 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Tests/FirebaseAuthSwiftUITests/ContentStateDefaultsTests.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Tests/FirebaseAuthSwiftUITests/ContentStateDefaultsTests.swift @@ -91,7 +91,7 @@ struct ContentStateDefaultsTests { func emailLinkContentState() { let state = EmailLinkContentState() #expect(state.email.wrappedValue.isEmpty) - #expect(!state.didSend) + #expect(!state.didSend && !state.needsEmailConfirmation) #expect(!state.isValid && !state.isLoading && state.errorMessage == nil) } diff --git a/FirebaseSwiftUI/README.md b/FirebaseSwiftUI/README.md index 306676dac1..ad6fb8aaac 100644 --- a/FirebaseSwiftUI/README.md +++ b/FirebaseSwiftUI/README.md @@ -244,6 +244,7 @@ When email link sign-in is configured: - Handles deep link navigation from email - Manages the complete email verification flow - Supports anonymous user upgrades via email link +- Asks for the email address when a link is opened on another device, unless `withEmailLinkSignIn(forceSameDevice: true)` limits links to the device that requested them #### 5. **Anonymous User Auto-Upgrade** @@ -1275,6 +1276,20 @@ Handles the email link flow when the user taps the link. Automatically routes to **Note:** This method handles both initial sign-in and reauthentication flows automatically. The behavior is determined by whether `sendEmailSignInLink(email:isReauth:)` was called with `isReauth: true`. +A link opened on a device that didn't request it throws `AuthServiceError.invalidEmailLink` as before, and also sets `pendingEmailLink` unless `withEmailLinkSignIn(forceSameDevice: true)` is set. Finish with `confirmEmailLinkSignIn(email:)`, passing the address the link was sent to. `AuthPickerView` handles links itself, opening the email-link screen when needed, so your own `onOpenURL` handler can stay: a call with a link already being handled waits for that attempt and gets its result, and a link that already signed in is ignored until sign-out. + +--- + +##### Confirm Email Link Sign-In + +```swift +public func confirmEmailLinkSignIn(email: String) async throws +``` + +Signs in with `pendingEmailLink`, a link opened on another device, once the user confirms the email address it was sent to. + +A used or expired link clears `pendingEmailLink`. Call `cancelEmailLinkConfirmation()` to drop it yourself, for example when the user wants a new link; signing out or closing the sheet also drops it. An app that shows its own email-link screen through `withEmailLinkSignIn(onTap:)` handles opened links on that screen. + --- #### Phone Authentication diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift new file mode 100644 index 0000000000..dcfb6e22f4 --- /dev/null +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift @@ -0,0 +1,281 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import FirebaseAuth +@testable import FirebaseAuthSwiftUI +import Foundation +import Testing + +/// Email-link sign-in when the link is opened on the device that sent it or on another one. +@Suite(.serialized) +@MainActor +struct EmailLinkDeviceTests { + private func makeService(continueURL: String = "https://flutterfire-e2e-tests.firebaseapp.com", + forceSameDevice: Bool = false) async throws -> AuthService { + configureFirebaseIfNeeded() + try await clearAuthEmulatorState() + let settings = makeEmailLinkActionCodeSettings() + settings.url = URL(string: continueURL) + return AuthService( + configuration: AuthConfiguration(emailLinkSignInActionCodeSettings: settings) + ) + .withEmailLinkSignIn(forceSameDevice: forceSameDevice) + } + + private func continueURLItems(of url: URL) throws -> [URLQueryItem] { + let link = try #require( + URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems? + .first { $0.name == "link" }?.value + ) + let continueURL = try #require( + URLComponents(string: link)?.queryItems?.first { $0.name == "continueUrl" }?.value + ) + return URLComponents(string: continueURL)?.queryItems ?? [] + } + + @Test + func continueURLKeepsAppQueryItems() async throws { + let service = try await makeService( + continueURL: "https://flutterfire-e2e-tests.firebaseapp.com/?app=1" + ) + let email = createEmail() + + // The configured settings are reused, so a second link must not repeat the first's items. + try await service.sendEmailSignInLink(email: createEmail()) + try await service.sendEmailSignInLink(email: email) + + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + let items = try continueURLItems(of: link) + #expect(items.filter { $0.name == "app" }.map(\.value) == ["1"]) + #expect(items.filter { $0.name == "ui_sid" }.count == 1) + #expect(items.first { $0.name == "ui_sd" }?.value == "0") + } + + @Test + func linkFromAnotherDeviceWaitsForEmailConfirmation() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + + // Another device has no stored email for the link. + service.emailLink = nil + await #expect(throws: AuthServiceError.self) { + try await service.handleSignInLink(url: link) + } + // Waits instead of signing in. Other tests share `Auth`, so its state isn't checked here. + #expect(service.pendingEmailLink == link) + + try await service.confirmEmailLinkSignIn(email: email) + try await waitForStateChange { + service.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame + } + #expect(service.pendingEmailLink == nil) + try await service.signOut() + } + + @Test + func linkFromAnotherSessionWaitsAndCanBeCancelled() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + + // This device sent a newer link since, so the stored email may not be this link's. + try await service.sendEmailSignInLink(email: createEmail()) + service.emailLink = email + // Throws as before, and keeps the link for confirmation. + await #expect(throws: AuthServiceError.self) { + try await service.handleSignInLink(url: link) + } + #expect(service.pendingEmailLink == link) + + service.cancelEmailLinkConfirmation() + #expect(service.pendingEmailLink == nil) + } + + @Test + func signingOutForgetsPendingLink() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + service.emailLink = nil + // Throws as before, and keeps the link for confirmation. + await #expect(throws: AuthServiceError.self) { + try await service.handleSignInLink(url: link) + } + #expect(service.pendingEmailLink == link) + + try await service.signOut() + + #expect(service.pendingEmailLink == nil) + #expect(service.incomingEmailLink == nil) + } + + @Test + func linkIsOnlyUsedOnce() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + + // Both `AuthPickerView` and an app's own `onOpenURL` may pass the same link. + try await service.handleSignInLink(url: link) + try await service.handleSignInLink(url: link) + + try await waitForStateChange { + service.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame + } + #expect(service.pendingEmailLink == nil) + try await service.signOut() + } + + @Test + func concurrentCallsShareOneAttempt() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + + let first = Task { try await service.handleSignInLink(url: link) } + let second = Task { try await service.handleSignInLink(url: link) } + try await first.value + try await second.value + + try await waitForStateChange { + service.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame + } + try await service.signOut() + } + + @Test + func concurrentCallsShareAFailure() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + // Another device: the first attempt fails, and the second must not report success. + service.emailLink = nil + + let first = Task { try await service.handleSignInLink(url: link) } + let second = Task { try await service.handleSignInLink(url: link) } + await #expect(throws: AuthServiceError.self) { try await first.value } + await #expect(throws: AuthServiceError.self) { try await second.value } + } + + @Test + func signingOutLetsAUsedLinkFailAgain() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + try await service.handleSignInLink(url: link) + try await service.signOut() + + // The link is used up; after sign-out it reports that instead of doing nothing. + await #expect(throws: (any Error).self) { + try await service.handleSignInLink(url: link) + } + } + + @Test + func forcedSameDeviceRejectsLinkFromAnotherDevice() async throws { + let service = try await makeService(forceSameDevice: true) + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + #expect(try continueURLItems(of: link).first { $0.name == "ui_sd" }?.value == "1") + + service.emailLink = nil + await #expect(throws: AuthServiceError.self) { + try await service.handleSignInLink(url: link) + } + #expect(service.pendingEmailLink == nil) + } + + @Test + func openedLinkPresentsEmailLinkScreen() throws { + configureFirebaseIfNeeded() + let service = AuthService().withEmailLinkSignIn() + var link = try #require(URLComponents(string: "https://example.com/")) + link.queryItems = [URLQueryItem( + name: "link", + value: "https://flutterfire-e2e-tests.firebaseapp.com/__/auth/action?apiKey=key" + + "&mode=signIn&oobCode=code&continueUrl=https://example.com" + )] + let url = try #require(link.url) + + service.presentEmailLinkScreen(for: url) + + #expect(service.isPresented) + #expect(service.authView == .emailLink) + #expect(service.incomingEmailLink == url) + + // Already showing: the screen's own handler takes the link. + service.incomingEmailLink = nil + service.presentEmailLinkScreen(for: url) + #expect(service.incomingEmailLink == nil) + #expect(service.navigator.routes == [.emailLink]) + } + + @Test + func openedLinkIsLeftToAppsOwnEmailLinkScreen() throws { + configureFirebaseIfNeeded() + let service = AuthService().withEmailLinkSignIn(onTap: {}) + var link = try #require(URLComponents(string: "https://example.com/")) + link.queryItems = [URLQueryItem( + name: "link", + value: "https://flutterfire-e2e-tests.firebaseapp.com/__/auth/action?apiKey=key" + + "&mode=signIn&oobCode=code&continueUrl=https://example.com" + )] + + let url = try #require(link.url) + service.presentEmailLinkScreen(for: url) + + #expect(!service.isPresented) + #expect(service.incomingEmailLink == nil) + } + + @Test + func onlyFirebaseSignInLinksCountAsEmailSignInLinks() throws { + configureFirebaseIfNeeded() + let service = AuthService().withEmailLinkSignIn() + var link = try #require(URLComponents(string: "https://example.com/")) + link.queryItems = [URLQueryItem( + name: "link", + value: "https://flutterfire-e2e-tests.firebaseapp.com/__/auth/action?apiKey=key" + + "&mode=signIn&oobCode=code&continueUrl=https://example.com" + )] + + #expect(try service.isEmailSignInLink(#require(link.url))) + // Another deep link, or a link to some other Firebase action, is left to the app. + #expect(try !service.isEmailSignInLink(#require(URL(string: "myapp://settings")))) + #expect(try !service.isEmailSignInLink( + #require(URL(string: "https://example.com/?link=https://example.com/?mode=resetPassword")) + )) + } + + @Test + func openedLinkIsIgnoredWithoutEmailLinkSignIn() throws { + configureFirebaseIfNeeded() + let service = AuthService() + let url = try #require(URL(string: "https://example.com/?link=https://example.com")) + + service.presentEmailLinkScreen(for: url) + + #expect(!service.isPresented) + #expect(service.navigator.routes.isEmpty) + } +}