diff --git a/FirebaseSwiftUI/README.md b/FirebaseSwiftUI/README.md index 1ea58b670d..312e055e2e 100644 --- a/FirebaseSwiftUI/README.md +++ b/FirebaseSwiftUI/README.md @@ -5,8 +5,9 @@ 1. [Installation](#installation) 2. [Getting Started](#getting-started) 3. [Usage with Default Views](#usage-with-default-views) -4. [Usage with Custom Views](#usage-with-custom-views) -5. [API Reference](#api-reference) +4. [Customizing Default Views](#customizing-default-views) +5. [Usage with Custom Views](#usage-with-custom-views) +6. [API Reference](#api-reference) --- @@ -287,6 +288,185 @@ The operation automatically retries after successful reauthentication. No additi --- +## Customizing Default Views + +Between the default views and fully custom views, you can restyle or replace parts of `AuthPickerView` while `AuthService` keeps driving navigation, MFA, account conflicts, reauthentication, loading state and errors. Every API in this section is available from `import FirebaseAuthSwiftUI`. + +### Theming + +Set fonts, text field and button styling for every screen in the auth sheet. Unset values keep the default look and leave your app's own `.font`, `.tint` and `.buttonBorderShape` in place. + +```swift +AuthPickerView { + HomeView() +} +.authTypography(AuthTypography(fontName: "AvenirNext-Regular")) +.authTextFieldStyle(AuthTextFieldStyle(tint: .indigo, cornerRadius: 12)) +.authCTAButtonStyle(AuthCTAButtonStyle(backgroundColor: .indigo, contentColor: .white, shape: .capsule)) +.environment(authService) +``` + +Apply the same typography to your own views inside the auth flow with `.authFont(_:weight:)`: + +```swift +Text("Welcome back") + .authFont(.title2, weight: .semibold) +``` + +### Replacing the First Screen + +Chain `.pickerContent`, `.pickerDestination` and `.signedInContent` directly on `AuthPickerView`, before theming or `.reauthContent`. Those return a plain `View`, which has no slot modifiers. + +`.pickerContent { }` keeps the stock first screen, `DefaultAuthPickerContent`, so you can add modifiers to it: + +```swift +AuthPickerView { authenticatedApp } + .pickerContent { + DefaultAuthPickerContent() + .background(Color.yellow.opacity(0.1)) + } +``` + +To keep the stock screen but lay out the provider buttons yourself, use `DefaultAuthPickerContent(authMethodPicker:)`. The closure receives an `AuthMethodPickerState`; call its `select` so MFA, account conflicts and errors are handled the same as the default buttons: + +```swift +AuthPickerView { authenticatedApp } + .pickerContent { + DefaultAuthPickerContent { state in + ForEach(state.providers, id: \.id) { provider in + Button(provider.displayName) { state.select(provider) } + } + if state.isEmailLinkEnabled { + Button("Email link", action: state.selectEmailLink) + } + } + } +``` + +`.pickerContent { state in }` replaces the whole first screen, including the logo, email form, terms and title. It receives the same `AuthMethodPickerState`, which also has `goToEmailSignIn` and `goToEmailSignUp` to push the `AuthView.signIn` and `AuthView.signUp` routes, shown as `SignInView` and `SignUpView` by default: + +```swift +AuthPickerView { authenticatedApp } + .pickerContent { state in + VStack { + Text("Welcome").authFont(.largeTitle) + ForEach(state.providers, id: \.id) { provider in + Button(provider.displayName) { state.select(provider) } + } + if state.isEmailSignInEnabled { + Button("Sign in with email", action: state.goToEmailSignIn) + // authService is the instance passed to .environment(authService) + if authService.allowNewEmailAccounts { + Button("Create account", action: state.goToEmailSignUp) + } + } + } + } +``` + +### Replacing Pushed Screens + +`.pickerDestination { screen in }` receives the `AuthView` being pushed. Return `DefaultAuthPickerDestination(screen:)` from a `default:` branch for the screens you don't replace, so routes added in future releases keep working: + +```swift +AuthPickerView { authenticatedApp } + .pickerDestination { screen in + switch screen { + case .enterPhoneNumber: + MyPhoneEntry() + default: + DefaultAuthPickerDestination(screen: screen) + } + } +``` + +### Screen Content Slots + +The sign-in and MFA screens each have a `*Screen` view that keeps the screen's logic (validation, sending codes, signing in) and passes its content a state value with actions, `isLoading` and a localized `errorMessage`, plus input bindings and `isValid` where the screen takes input. A matching `Default*Content` view draws the stock markup, so you can reuse it for some states. + +| Screen | Default content | +|--------|-----------------| +| `EmailAuthScreen` | `DefaultEmailAuthContent` | +| `PasswordRecoveryScreen` | `DefaultPasswordRecoveryContent` | +| `EmailLinkScreen` | `DefaultEmailLinkContent` | +| `EnterPhoneNumberScreen` | `DefaultEnterPhoneNumberContent` | +| `EnterVerificationCodeScreen` | `DefaultEnterVerificationCodeContent` | +| `MFAEnrolmentScreen` | `DefaultMFAEnrolmentContent` | +| `MFAResolutionScreen` | `DefaultMFAResolutionContent` | +| `MFAManagementScreen` | `DefaultMFAManagementContent` | + +Use them from `.pickerDestination` (or `.pickerContent` for `EmailAuthScreen`). Update password has no content slot. The reauthentication prompts have their own screens, customized with `.reauthContent` below. + +`EmailAuthScreen`, `PasswordRecoveryScreen` and `EmailLinkScreen` leave error display to your content: show `state.errorMessage` (and call `state.dismissError` where the state has it), or the error isn't shown. The other screens also raise the sheet's error alert, so showing `errorMessage` there as well shows the error twice. + +```swift +AuthPickerView { authenticatedApp } + .pickerDestination { screen in + switch screen { + case .enterPhoneNumber: + EnterPhoneNumberScreen { state in + TextField("Phone number", text: state.phoneNumber) + Button("Send code", action: state.sendCode) + .disabled(!state.isValid || state.isLoading) + } + default: + DefaultAuthPickerDestination(screen: screen) + } + } +``` + +### Signed-In and Reauthentication Content + +`.signedInContent { state in }` replaces the screen shown to signed-in users. The `SignedInContentState` carries the user and actions such as `signOut` and `deleteAccount`; wrap `DefaultSignedInContent(state:)` to keep the stock markup. + +```swift +AuthPickerView { authenticatedApp } + .signedInContent { state in + MyAccountView( + email: state.user?.email, + onDeleteAccount: state.deleteAccount, + onSignOut: state.signOut + ) + } +``` + +`.reauthContent { prompt in }` replaces the password, phone and email-link reauthentication prompts. The closure receives a `ReauthPrompt` (`.password`, `.phone` or `.emailLink`, each with its content state). Keep a `default:` branch that returns `DefaultReauthContent(prompt:)`: + +```swift +AuthPickerView { authenticatedApp } + .reauthContent { prompt in + switch prompt { + case let .password(state): + SecureField("Password", text: state.password) + Button("Confirm", action: state.verify) + .disabled(!state.isValid || state.isLoading) + Button("Cancel", action: state.cancel) + default: + DefaultReauthContent(prompt: prompt) + } + } +``` + +`.reauthContent` is a `View` modifier, so apply it after the `AuthPickerView` slot modifiers. The OAuth reauthentication prompt, the confirmation alerts before phone and email-link reauthentication, and the second-factor step when an MFA-enrolled user reauthenticates stay stock. + +### Starting Sign-In Programmatically + +`AuthService.registeredProviders` lists the providers registered with `registerProvider(providerWithButton:)`, and `AuthService.triggerSignIn(for:)` starts sign-in for one without rendering its button. Credential-based providers work as is. A custom provider that presents its own screens first can adopt `AuthProviderAction`, so `triggerSignIn(for:)` and `AuthMethodPickerState.select` can start it: + +```swift +final class MyProviderAuthUI: AuthProviderAction { + let authService: AuthService + // id, displayName, provider and authButton() as for any AuthProviderUI + + @MainActor func triggerAction() async throws -> SignInOutcome? { + let credential = try await presentMySignInScreen() + return try await authService.signIn(credentials: credential) + } +} +``` + +--- + ## Usage with Custom Views If you need more control over the UI or navigation flow, you can build your own custom authentication views while still leveraging the `AuthService` for authentication logic. @@ -658,7 +838,7 @@ When building custom views, you need to handle several things yourself that `Aut ### Reauthentication in Custom Views -When building custom views, handle reauthentication by catching specific errors and implementing your own flow. Sensitive operations throw four types of reauthentication errors, each containing context information. +When building custom views, handle reauthentication by catching specific errors and implementing your own flow. There are five types of reauthentication errors: four thrown by sensitive operations, each containing context information, and `multiFactorReauthenticationRequired`, thrown while reauthenticating a user with enrolled second factors. #### Implementation Patterns @@ -748,6 +928,35 @@ do { } ``` +**Multi-Factor Authentication:** + +`reauthenticate(with:)`, `reauthenticate(context:)` and `handleSignInLink(url:)` (for an email-link reauthentication) throw `multiFactorReauthenticationRequired` when the user has enrolled second factors. Resolve it as for sign-in MFA: send an SMS code with `resolveSmsChallenge(hintIndex:)` for phone hints, then call `resolveSignIn(code:hintIndex:verificationId:)`: + +```swift +do { + try await authService.reauthenticate(with: credential) +} catch let error as AuthServiceError { + guard case .multiFactorReauthenticationRequired(let mfaRequired) = error else { + throw error + } + let hintIndex = 0 // Let the user pick from mfaRequired.hints + switch mfaRequired.hints[hintIndex] { + case .phone: + let verificationId = try await authService.resolveSmsChallenge(hintIndex: hintIndex) + let code = await promptUserForSMSCode() + try await authService.resolveSignIn( + code: code, + hintIndex: hintIndex, + verificationId: verificationId + ) + case .totp: + let code = await promptUserForTOTPCode() + try await authService.resolveSignIn(code: code, hintIndex: hintIndex) + } +} +try await authService.deleteUser() // Retry +``` + All reauthentication context objects include a `.displayMessage` property for user-facing text. ### Custom OAuth Providers @@ -811,7 +1020,7 @@ Override any UI string by creating a `Localizable.strings` (or `.xcstrings`) fil let configuration = AuthConfiguration(customStringsBundle: .main) ``` -See [example implementation](../../samples/swiftui/FirebaseSwiftUISample/FirebaseSwiftUISample) for a working demo. +See [example implementation](../samples/swiftui/FirebaseSwiftUISample/FirebaseSwiftUISample) for a working demo. --- @@ -925,6 +1134,22 @@ authService --- +##### Email Link Authentication + +```swift +public func withEmailLinkSignIn(forceSameDevice: Bool = false) -> AuthService +public func withEmailLinkSignIn(forceSameDevice: Bool = false, + onTap: @escaping () -> Void) -> AuthService +``` + +Enables email-link (passwordless) sign-in. Its button pushes the email-link screen, or runs `onTap` when you pass one. Requires `emailLinkSignInActionCodeSettings` in `AuthConfiguration`. + +**Parameters:** +- `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`. +- `onTap`: Runs when the email-link button is tapped, for an app that shows its own email-link screen. + +--- + ##### Phone Authentication ```swift @@ -1101,6 +1326,33 @@ authService.registerProvider(providerWithButton: customProvider) --- +#### Registered Providers + +```swift +public var registeredProviders: [AuthProviderUI] { get } +``` + +The providers registered with `registerProvider(providerWithButton:)`, in registration order. Email and email-link sign-in aren't included. + +--- + +#### Triggering Sign-In + +```swift +public func triggerSignIn(for provider: AuthProviderUI) async throws -> SignInOutcome? +``` + +Starts sign-in with a registered provider without rendering its button. `AuthProviderAction` providers run `triggerAction()` and return its outcome; other credential-based providers sign in through `signIn(_:)`. + +**Parameters:** +- `provider`: A provider from `registeredProviders`. + +**Returns:** The sign-in outcome, for example `.mfaRequired` when a second factor is needed. + +**Throws:** `AuthServiceError.providerAuthenticationFailed` for a provider that is neither credential-based nor an `AuthProviderAction`, or the provider's sign-in error. + +--- + #### Rendering Authentication Buttons ```swift @@ -1272,7 +1524,7 @@ Handles the email link flow when the user taps the link. Automatically routes to **Parameters:** - `url`: The deep link URL from the email -**Throws:** `AuthServiceError` or Firebase Auth errors +**Throws:** `AuthServiceError.multiFactorReauthenticationRequired(MFARequired)` when an email-link reauthentication finds enrolled second factors, other `AuthServiceError` cases, or Firebase Auth errors **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`. @@ -1418,7 +1670,7 @@ Reauthenticates the current user with an OAuth provider (Google, Apple, Facebook **Parameters:** - `context`: The reauth context from `oauthReauthenticationRequired` error -**Throws:** `AuthServiceError.noCurrentUser` or `AuthServiceError.providerNotFound` +**Throws:** `AuthServiceError.noCurrentUser`, `AuthServiceError.providerNotFound`, or `AuthServiceError.multiFactorReauthenticationRequired(MFARequired)` when the user has enrolled second factors **Note:** Only works for OAuth providers. For email/phone, use `reauthenticate(with:)`. @@ -1435,7 +1687,7 @@ Reauthenticates the current user with a pre-obtained authentication credential. **Parameters:** - `credential`: The authentication credential (from `EmailAuthProvider` or `PhoneAuthProvider`) -**Throws:** `AuthServiceError.noCurrentUser` or Firebase Auth errors +**Throws:** `AuthServiceError.noCurrentUser`, `AuthServiceError.multiFactorReauthenticationRequired(MFARequired)` when the user has enrolled second factors, or Firebase Auth errors --- @@ -1646,6 +1898,33 @@ AuthPickerView { .environment(authService) ``` +**Modifiers:** + +```swift +public func pickerContent( + @ViewBuilder _ pickerContent: @escaping () -> NewPickerContent +) -> AuthPickerContent<...> + +public func pickerContent( + @ViewBuilder _ pickerContent: @escaping (AuthMethodPickerState) -> NewPickerContent +) -> AuthPickerContent<...> + +public func pickerDestination( + @ViewBuilder _ destination: @escaping (AuthView) -> NewDestinationContent +) -> AuthPickerContent<...> + +public func signedInContent( + @ViewBuilder _ signedInContent: @escaping (SignedInContentState) -> NewSignedInContent +) -> AuthPickerContent<...> +``` + +- `pickerContent { }`: Replaces the signed-out first screen, usually with `DefaultAuthPickerContent` plus your modifiers. +- `pickerContent { state in }`: Replaces the whole first screen, receiving an `AuthMethodPickerState`. +- `pickerDestination { screen in }`: Replaces pushed screens. Return `DefaultAuthPickerDestination(screen:)` from a `default:` branch. +- `signedInContent { state in }`: Replaces the signed-in screen. `DefaultSignedInContent(state:)` holds the stock markup. + +Each returns an `AuthPickerContent`, which has the same four modifiers, so they can be chained. `.reauthContent { prompt in }` is a `View` modifier that replaces the reauthentication prompts inside the view it's applied to. See [Customizing Default Views](#customizing-default-views). + **Behavior:** - Presents authentication UI as a modal sheet controlled by `authService.isPresented` - Automatically handles navigation between auth screens @@ -1696,21 +1975,49 @@ Types of second factors for MFA. --- +#### AuthView + +```swift +public enum AuthView: Hashable { + case passwordRecovery + case signIn + case signUp + case emailLink + case updatePassword + case mfaEnrollment + case mfaManagement + case mfaResolution(MFARequired) + case enterPhoneNumber + case enterVerificationCode(verificationID: String, fullPhoneNumber: String) +} +``` + +Screens pushed inside the authentication sheet, received by `.pickerDestination`. `signIn` and `signUp` are separate email and password screens, shown as `SignInView` and `SignUpView` by default and reached with `AuthMethodPickerState.goToEmailSignIn` and `goToEmailSignUp`. New cases may be added in future releases, so keep a `default:` branch when switching over `AuthView`. + +--- + #### AuthServiceError ```swift -public enum AuthServiceError: Error { +public enum AuthServiceError: LocalizedError { case noCurrentUser - case notConfiguredActionCodeSettings(String) case invalidEmailLink(String) - case providerNotFound(String) - case invalidCredentials(String) - case multiFactorAuth(String) + case clientIdNotFound(String) + case notConfiguredActionCodeSettings(String) case oauthReauthenticationRequired(context: OAuthReauthContext) case emailReauthenticationRequired(context: EmailReauthContext) case emailLinkReauthenticationRequired(context: EmailLinkReauthContext) case phoneReauthenticationRequired(context: PhoneReauthContext) + case multiFactorReauthenticationRequired(MFARequired) + case invalidCredentials(String) + case signInFailed(underlying: Error) case accountConflict(AccountConflictContext) + case legacySignInRecoveryPresented + case providerNotFound(String) + case multiFactorAuth(String) + case rootViewControllerNotFound(String) + case providerAuthenticationFailed(String) + case signInCancelled(String) } ``` @@ -1728,7 +2035,7 @@ Thrown by sensitive operations when Firebase requires recent authentication. Eac - **`phoneReauthenticationRequired(context: PhoneReauthContext)`**: Phone provider. Context contains `phoneNumber` and `displayMessage`. Handle SMS verification, then call `reauthenticate(with:)`. -- **`multiFactorReauthenticationRequired(MFARequired)`**: Thrown by `reauthenticate(with:)` and `reauthenticate(context:)` when the user has enrolled second factors. Complete it as for sign-in MFA resolution: `resolveSmsChallenge(hintIndex:)` for SMS hints, then `resolveSignIn(code:hintIndex:verificationId:)`. Default views handle this inside the reauthentication sheet. +- **`multiFactorReauthenticationRequired(MFARequired)`**: Thrown by `reauthenticate(with:)`, `reauthenticate(context:)` and `handleSignInLink(url:)` (for an email-link reauthentication) when the user has enrolled second factors. Complete it as for sign-in MFA resolution: `resolveSmsChallenge(hintIndex:)` for SMS hints, then `resolveSignIn(code:hintIndex:verificationId:)`. Default views handle this inside the reauthentication sheet. --- @@ -1752,7 +2059,7 @@ Thrown by sensitive operations when Firebase requires recent authentication. Eac ## Additional Resources -- [Sample SwiftUI App](https://github.com/firebase/FirebaseUI-iOS/tree/main/samples/swiftui/FirebaseSwiftUIExample) +- [Sample SwiftUI App](https://github.com/firebase/FirebaseUI-iOS/tree/main/samples/swiftui/FirebaseSwiftUISample) - [Firebase iOS Setup Guide](https://firebase.google.com/docs/ios/setup) - [Firebase Authentication Documentation](https://firebase.google.com/docs/auth) - [FirebaseUI-iOS GitHub Repository](https://github.com/firebase/FirebaseUI-iOS) diff --git a/GETTING_STARTED.md b/GETTING_STARTED.md index 03b0961beb..3548fe2433 100644 --- a/GETTING_STARTED.md +++ b/GETTING_STARTED.md @@ -392,6 +392,8 @@ let configuration = AuthConfiguration( ) ``` +To restyle or partly replace the default views, theme them with `.authTypography(_:)`, `.authTextFieldStyle(_:)` and `.authCTAButtonStyle(_:)`, swap in your own screens with the `AuthPickerView` content slots (`.pickerContent`, `.pickerDestination` and `.signedInContent`), and replace the reauthentication prompts with `.reauthContent`, while `AuthService` keeps handling navigation, MFA and account conflicts. See [Customizing Default Views](https://github.com/firebase/FirebaseUI-iOS/blob/main/FirebaseSwiftUI/README.md#customizing-default-views). + If you want to keep the built-in buttons but use your own layout, call `authService.renderButtons()`. If you want a fully custom experience, build your own views and call methods such as: