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
329 changes: 238 additions & 91 deletions FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ public struct EmailLinkReauthScreen<Content: View>: 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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -51,6 +65,9 @@ public struct EmailLinkContentState {
public init(email: Binding<String> = .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,
Expand All @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -116,6 +137,9 @@ public struct EmailLinkScreen<Content: View>: View {
email: $email,
sendSignInLink: sendSignInLink,
dismissAlert: { didSend = false },
confirmEmail: confirmEmail,
cancelConfirmation: { authService.cancelEmailLinkConfirmation() },
needsEmailConfirmation: authService.pendingEmailLink != nil,
didSend: didSend,
isValid: isValid,
isLoading: isLoading,
Expand All @@ -125,32 +149,24 @@ public struct EmailLinkScreen<Content: View>: 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) }
}
Comment thread
demolaf marked this conversation as resolved.
Resolved
.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
Expand All @@ -166,6 +182,41 @@ public struct EmailLinkScreen<Content: View>: 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
Expand All @@ -176,7 +227,6 @@ public struct EmailLinkScreen<Content: View>: View {
do {
try await authService.sendEmailSignInLink(email: email)
didSend = true
authService.emailLink = email
} catch {
if shouldShowErrorAlert(for: error) {
errorMessage = authService.string.localizedErrorMessage(for: error)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
15 changes: 15 additions & 0 deletions FirebaseSwiftUI/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**

Expand Down Expand Up @@ -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
Expand Down
Loading
Loading