# Sign-in

Sign-in in a generated app has two parts, each from a module of its own:

| Part | Module | What it brings |
| --- | --- | --- |
| The screens | [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) | The sign-in, the sign-up and the password reset for an email address and a password, with a button for each other way to sign in of the app, the screen of the account with its entry on the settings screen, and the two guards of the routes that show them. |
| The session and the accounts | A module that provides the auth role, among the built-in modules [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) | `appSession`, which knows who uses the app and through which code signs in, up and out, and the service that keeps the accounts, here Firebase Authentication. |
| Other ways to sign in | [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md), [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) | Sign-in with a Google account on Android and iOS, and with an Apple Account on iOS; see [ways to sign in](#ways-to-sign-in). |

The screens need the session, so `sign_in` brings `firebase_auth` with it:

```bash
smf create my_app -m home,sign_in,bloc,bottom_tabs
```

An app can also have the session without the screens, with `-m firebase_auth` alone. Its screens that sign a user in are then yours to write; see [an app without the screens](#an-app-without-the-screens).

![The sign-in in the light theme, in English: the cell Ma 5 among the cells of a table, the title Sign in with the line Choose how to sign in to your account. below it, the white buttons Continue with Google and Continue with Apple, then or, the fields Email and Password, Forgot password? below the password field, the button Sign in, and Create account in green below it.](https://doc.saymyframe.com/demo/0.8/app_sign_in.png)
![The sign-in in the dark theme, in Ukrainian: the title Вхід, the white buttons Продовжити з Google and Продовжити з Apple, the fields Електронна пошта and Пароль, the light button Увійти, and Створити акаунт in green below it.](https://doc.saymyframe.com/demo/0.8/app_sign_in_dark_uk.png)

These are the screens of an app with [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) and [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) too, whose buttons are above the form; see [ways to sign in](#ways-to-sign-in).

| File | From | What it holds |
| --- | --- | --- |
| `lib/features/sign_in/` | `sign_in` | The screens, their state and the functions of the guards. |
| `lib/core/auth/app_session.dart` | the auth role | `appSession`, the session of the app, and `authMode`, who may use the app without an account. |
| `lib/core/auth/guest_data.dart` | the auth role | `takeGuestData()`, which you edit: what moves to an account from the anonymous user who signs in to it. |
| `lib/core/auth/auth_service.dart` | the auth role | `AuthService`, which the module that provides the role implements. The code of the app does not use it. |
| `lib/core/auth/sign_in_methods.dart` | the auth role | `appSignInMethods`, the ways to sign in with Google, Apple or another identity provider that the modules of the app add. |
| `lib/core/auth/firebase_auth_service.dart` | `firebase_auth` | The service on Firebase Authentication. |
| `tool/enable_firebase_sign_in.dart` | `firebase_auth` | The script that [enables the sign-in methods](https://doc.saymyframe.com/guides/firebase.md#sign-in-methods-of-firebase-authentication) in the Firebase project. |

## The mode

The mode of the app says who may use it without an account. A run in a terminal asks for it, and `--auth-mode` answers in advance:

```text
? Who may use the app without an account? (↑↓ to move, enter to choose)
❯ Nobody: the user signs in first
  Everyone: an account only where a screen needs one
  Everyone, as an anonymous user with an id from the start
```

| `--auth-mode` | Who may use the app without an account | With `sign_in`, what the user sees |
| --- | --- | --- |
| `required`, the default | Nobody. | The sign-in in place of every screen, until the user is signed in to an account. With an [onboarding](https://doc.saymyframe.com/modules/onboarding.md), the onboarding comes first. |
| `guest` | Everyone. The app has no user until someone signs in. | The app. The sign-in opens over a page when the user asks for a screen that needs an account, such as the screen of the account. |
| `anonymous` | Everyone, as an anonymous user that the app signs in itself when it starts. Code then has the id of a user, `appSession.value.uid`, before anyone has an account. | The same as in `guest`. Signing up gives the anonymous user the account, with the same id. |

A run without a terminal takes `required` when the option is not given, and does not stop for it. The auth role writes the mode into the app as a constant:

```dart title="lib/core/auth/app_session.dart"
const AuthMode authMode = AuthMode.required;
```

To change the mode later, change that value, and keep the declaration as it is, on a line that it starts: the script that enables the sign-in methods reads the mode from that line. The module that provides sign-in has to allow what the mode needs. With `firebase_auth`, the mode `anonymous` needs anonymous users enabled in the Firebase project, which the script does when you run it again.

### An anonymous user from the start

In the mode `anonymous`, an app without a user signs in anonymously when it starts, and waits for that for at most 3 seconds. When the sign-in fails or takes longer, the app starts without a user. So code handles a `SignedOutSession` in this mode too.

The app tries again each time the user comes back to it, and after each call that leaves nobody signed in, such as a sign-out or the deletion of an account. A sign-in that took longer than the wait still becomes the session when it comes. In debug mode the app prints the error of an anonymous sign-in that failed.

## What keeps a user from a screen

The mode keeps nobody from a screen on its own. A [guard of the routes](https://doc.saymyframe.com/guides/navigation.md#guards) does, and the session has the two values that such guards read:

| | A guard that reads it |
| --- | --- |
| `appSession.allowsApp` | Stands before the whole app. It is `true` for the user of an account, and in the modes `guest` and `anonymous` for everyone. |
| `appSession.hasAccount` | Stands only before the routes that it lists, the screens that need an account. It is `true` only for the user of an account, which an anonymous user is not. |

Both are a `ValueListenable<bool>` that is computed from the session when it is read, and their listeners are those of the session. So a guard never finds one of them changed and the other not.

`sign_in` declares both guards, `sign_in.gate` and `sign_in.hasAccount`, whose target is the sign-in. This is `routeGuards` of an app with the module and an onboarding:

```dart title="lib/core/router/app_router.dart"
final List<RouteGuard> routeGuards = [
  RouteGuard(
    'onboarding.firstRun',
    allows: guard0.onboardingCompleted(),
    redirectTo: const OnboardingOnboardingLocation(),
    flow: const {'onboarding.onboarding'},
  ),
  RouteGuard(
    'sign_in.gate',
    allows: guard1.signInAllowsApp(),
    redirectTo: const SignInSignInLocation(),
    flow: const {'sign_in.signIn', 'sign_in.signUp', 'sign_in.resetPassword'},
    resumes: false,
  ),
  RouteGuard(
    'sign_in.hasAccount',
    allows: guard1.signInHasAccount(),
    redirectTo: const SignInSignInLocation(),
    flow: const {'sign_in.signIn', 'sign_in.signUp', 'sign_in.resetPassword'},
    resumes: false,
    routes: const {'sign_in.account'},
  ),
];
```

- The screens of the sign-in only change the session. They neither close themselves nor navigate after a sign-in or a sign-out: the router does both when the guards change. See [after a guard changed](https://doc.saymyframe.com/guides/navigation.md#after-a-guard-changed).
- After a sign-out, the next user comes to the screen that the app starts on, and not to the screen that the last one was on.
- Once the user is signed in to an account, a navigation to a route of the sign-in, such as a link, shows the screen that the app starts on.

### A screen of yours that needs an account

To keep users without an account from a screen of yours, add the full name of its route to the `routes` of `sign_in.hasAccount`, and the names of the routes below it too. In this sketch they are the two routes of a feature `orders` of your own:

```dart title="lib/core/router/app_router.dart"
    routes: const {'sign_in.account', 'orders.orders', 'orders.order'},
```

A request for such a route opens the sign-in over the page that the user is on, and the route shows once the user is signed in. Such a route is outside the main navigation, and the app does not start on it.

### A screen of yours that offers to sign in

In the modes `guest` and `anonymous`, a screen may offer to sign in. Open the sign-in with `push()`, so that back leads back:

```dart
context.nav.signIn.signIn().push<void>()
```

In the mode `required`, no code navigates to the sign-in: the gate shows it.

## The account

The settings screen has the entry Account, which shows the email address of the account, or Not signed in. A tap opens the screen of the account, where the user signs out or deletes the account after a confirmation in a sheet. For a user without an account, in the modes `guest` and `anonymous`, the sign-in opens over the settings screen first.

![The settings screen in the light theme, in English: one card with the row Account, which shows ada.lovelace@example.com and an arrow, the row Subscription with Not active, then the row Language, the entry Theme, the row Notifications and the row Restore purchases. Below is the tab bar with Settings selected.](https://doc.saymyframe.com/demo/0.8/app_settings_account.png)
![The screen of the account: a back button, the title Account, the line You are signed in to this account:, a card with ada.lovelace@example.com, the button Sign out, and Delete account in red below it.](https://doc.saymyframe.com/demo/0.8/app_account.png)
![The screen of the account in the dark theme, in Ukrainian: the title Акаунт, the address of the account, the light button Вийти, and Видалити акаунт in red.](https://doc.saymyframe.com/demo/0.8/app_account_dark_uk.png)

The entry is within reach where the settings screen is. With a main navigation, such as that of [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md), the settings screen is one of its destinations. In an app without one, a screen of yours opens the settings screen, or the account directly; see [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md#where-the-entry-is-within-reach).

## Ways to sign in

Besides an email address and a password, a user can sign in with an account at an identity provider, such as Google or Apple. Each such way to sign in comes from a module of its own, which knows no provider of sign-in:

```bash
smf create my_app -m home,sign_in,bloc,bottom_tabs,google_sign_in,apple_sign_in
```

| Module | Way to sign in | Platforms |
| --- | --- | --- |
| [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) | Continue with Google | Android and iOS |
| [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) | Continue with Apple | iOS |

The module gives the auth role its way to sign in: the label and the icon of its button, the platforms that it works on, the function that asks the identity provider for a credential, and the issuer of the tokens of the identity provider. The role lists the ways to sign in of the app in `appSignInMethods` of `lib/core/auth/sign_in_methods.dart`, in the order of the modules:

```dart title="lib/core/auth/sign_in_methods.dart"
const List<SignInMethod> appSignInMethods = [
  SignInMethod(
    label: _googleSignInLabel,
    icon: method0.GoogleSignInIcon(),
    platforms: {TargetPlatform.android, TargetPlatform.iOS},
    credential: method0.googleCredential,
    issuer: 'https://accounts.google.com',
  ),
  SignInMethod(
    label: _appleSignInLabel,
    icon: method1.AppleSignInIcon(),
    platforms: {TargetPlatform.iOS},
    credential: method1.appleCredential,
    issuer: 'https://appleid.apple.com',
    revokesOnDeletion: true,
  ),
];
```

The sign-in and the sign-up of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md#other-ways-to-sign-in) show a button for each way to sign in whose `isAvailable` is true on the platform of the app, above the form. In an app without such a module the list is empty, and the screens show the form alone.

### What a tap does

The state of the screen calls the `credential` function of the way to sign in, which shows the sheet of its identity provider and returns a credential, and gives the credential to `appSession.signInWith`:

```dart
final credential = await method.credential();
if (credential == null) return; // The user closed the sheet.
await appSession.signInWith(credential);
```

- A function that returns `null` means that the user closed the sheet. That is no failure, and the screen goes back to how it was.
- A user of an account, or someone signed out, signs in with the credential at once.
- An anonymous user gets the identity and keeps the id. When the identity has an account already, the session signs in to that account with the same credential, and [the data of the guest](#the-data-of-a-guest) moves to it, as with a password. That sign-in may also fail with `accountExistsWithOtherMethod`, because the address of the identity has an account that signs in in another way: the provider of sign-in decides which.
- Call the function from the state of a screen and never within a call of `appSession`, which runs one call after another and would wait for it.

`AccountSession.issuers` lists the identity providers of the account, each the `issuer` of a `SignInMethod`.

### Deleting such an account

The App Store asks an app with Sign in with Apple to revoke the tokens that Apple gave it when the user deletes the account. A way to sign in that needs this has `revokesOnDeletion`. For an account with such a way, on a platform where it works, `appSession.deleteAccount()` calls its `credential` function itself, and the sheet of the identity provider shows again. The provider of sign-in signs the user in again with the new credential, revokes the tokens and deletes the account. When the user closes the sheet, the call completes and deletes nothing. A confirmation with another account fails with `invalidCredentials`, and a revocation that fails with `notConfigured`. Neither deletes anything.

### The provider of sign-in

The provider of the auth role takes the credentials and sets up its backend for each way to sign in. [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md#google-and-apple) takes those of Google and Apple. It reports a way to sign in of another identity provider when the app is generated, and `smf create` leaves the module of that way out, or stops with `--strict`. Its script enables Google in the Firebase project and sets up what Google needs, and its section of the README tells how to enable Apple; see [Firebase](https://doc.saymyframe.com/guides/firebase.md#sign-in-methods-of-firebase-authentication). Until a way to sign in is set up, signing in with it fails with `notConfigured`. What no command can set up is a step by hand, and the run ends with a link to the guides of those steps: Apple in the Firebase console with its key (guides of [the provider](https://doc.saymyframe.com/setup/firebase-auth-apple-provider.md) and of [the key](https://doc.saymyframe.com/setup/firebase-auth-apple-revocation.md)), the SHA of the release keys for Google ([guide](https://doc.saymyframe.com/setup/firebase-auth-google-release-sha.md)), and, for Sign in with Apple, signing the iOS app with a paid Apple Developer team ([guide](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md)).

### The App Store

App Store Review Guideline 4.8 asks an app on iOS that offers a login service of a third party, such as Google sign-in, to offer an equivalent way to sign in too: one that asks for no more than the name and the email address of the user and lets the user keep the address private. The App Store takes Sign in with Apple as such a way. `smf create` warns of an app without one, and the section "Sign-in" of its README says that the review may reject it:

```text
[WARN] [role:auth]: The app offers Continue with Google on iOS, a login service of a third party, but no way to sign in that the App Store takes as an equivalent: one that asks for no more than the name and the email address of the user and lets the user keep the address private (App Store Review Guideline 4.8). (Add such a way to sign in on iOS, such as Sign in with Apple.)
```

With `--strict`, the warning `auth.no_equivalent_sign_in` stops the run; see [lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict). Add `apple_sign_in` next to `google_sign_in`, and the warning goes away.

## The session

`appSession` is the one session of the app. Its `value` is an `AppSession`, and it notifies its listeners when that changes:

| `appSession.value` | Who uses the app |
| --- | --- |
| `SignedOutSession` | Nobody that the app knows. Its `uid` is `null`. |
| `AnonymousSession` | An anonymous user: one without an account, whom the app signed in itself. It has the `uid` of that user. |
| `AccountSession` | The user of an account. It has the `uid` and the `email` of the account, which is `null` if the account has none, and the `issuers` of its ways to sign in with an identity provider. |

`bootstrap()` starts the session in its platform phase, with `await initAuth()`, so the app knows who is signed in before its first frame.

A widget of an app with `sign_in` reads who uses the app from the state manager, and rebuilds when the user signs in or out: `context.watch<SessionCubit>().state` with `bloc`, and `ref.watch(sessionProvider)` with `riverpod`. In an app without the module, a widget follows `appSession` with a `ValueListenableBuilder`.

Code signs in, up and out through `appSession`, as the state of the screens of `sign_in` does:

| Call | What it does |
| --- | --- |
| `appSession.signIn(email:, password:)` | Signs in to the account. An anonymous user becomes the user of that account, and [the data of the guest](#the-data-of-a-guest) moves to it. |
| `appSession.signUp(email:, password:)` | Creates an account and signs in to it. An anonymous user gets the account and keeps the id, so everything that the user had stays. |
| `appSession.signInWith(credential)` | Signs in with the credential of a [way to sign in](#what-a-tap-does). An anonymous user gets the identity and keeps the id, or signs in to the account that has it. |
| `appSession.sendPasswordReset(email)` | Sends the message with which the owner of the account sets a new password. It completes whether the address has an account or not. |
| `appSession.signOut()` | Signs the user out. |
| `appSession.deleteAccount()` | Deletes the user who is signed in. The app is then without a user, as after a sign-out. For an account with a way to sign in that revokes on deletion, it [asks the identity provider again](#deleting-such-an-account) first. |

The calls run one after another, in the order they were made, so the user of the app is the result of the call that was made last.

The code of the app creates no other `AppSessionController`, and it calls neither `initAuth()` nor `createAuthService()` nor `appSession.start()`.

### A token for your server

A server of the app tells who the user is by a token. `appSession.userToken()` gives the token of the user, and `null` when nobody is signed in. An anonymous user has one too. The provider of sign-in keeps it and renews it, so read it for each request rather than keep it. When a server refuses a token, `appSession.userTokenAfter(rejected)` gives the one to use instead.

With [the REST client](https://doc.saymyframe.com/guides/rest.md#the-token-of-the-user), you need neither call: `appRest` adds the token to each request to the address of your API. The server checks the token itself. With [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md), it is a Firebase ID token, which a server verifies with the [Firebase Admin SDK](https://firebase.google.com/docs/auth/admin/verify-id-tokens). The Admin SDK takes only a token of its own Firebase project, so a token of another project fails there.

## Failures

A call of `appSession` fails only with an `AuthFailure`, whose `reason` the app shows a text for. The screens of `sign_in` have a text for every reason, in `authFailureText()` of `lib/features/sign_in/sign_in_widgets.dart`. Code of yours catches the failure the same way:

```dart
import 'core/auth/app_session.dart';

Future<String?> signIn(String email, String password) async {
  try {
    await appSession.signIn(email: email, password: password);
    return null;
  } on AuthFailure catch (failure) {
    return switch (failure.reason) {
      AuthFailureReason.invalidCredentials => 'Wrong email or password.',
      AuthFailureReason.network => 'No connection. Try again.',
      _ => 'Sign-in is unavailable.',
    };
  }
}
```

`app_session.dart` exports `AuthFailure` and `AuthFailureReason`, so the code of the app imports that file alone.

| Reason | What happened |
| --- | --- |
| `invalidCredentials` | The email address and the password match no account. A wrong password and an address without an account are this one reason, so that nobody learns from the app which addresses have an account. |
| `emailInUse` | The email address has an account already. |
| `credentialInUse` | The identity of a way to sign in belongs to another account already. |
| `accountExistsWithOtherMethod` | The email address of the identity has an account that signs in in another way. |
| `weakPassword` | The provider takes no password as weak as this one. |
| `invalidEmail` | The text is no email address. |
| `userDisabled` | The account is disabled. |
| `tooManyAttempts` | Too many attempts: the provider takes no more for a while. |
| `network` | The device did not reach the provider. |
| `recentSignInRequired` | The call needs a user who signed in a short while ago, as the deletion of an account does. Tell the user to sign out and sign in again. It is also the reason of a call for a user whose session has ended on the server, and that user is signed out on the device by then. |
| `notConfigured` | Sign-in is not set up at the provider, such as a way to sign in that is not enabled there, or one whose identity provider the provider does not take. This is a mistake in the setup of the app. |
| `unknown` | Anything else. |

A failure may have a `developerHint`: what went wrong in the words of the provider. It is for you and not for the user, so show it in debug mode only, as the screens of `sign_in` do below the text of the failure. For `notConfigured` it explains the mistake, and for `unknown` it has the error.

## The data of a guest

When an anonymous user signs in to an account that exists already, the user of the app changes from the guest to that account. What the app keeps under the id of the guest, such as a cart on a server, would be left behind. `takeGuestData()` says what moves:

```dart title="lib/core/auth/guest_data.dart"
Future<GiveGuestData?> takeGuestData(String guestUid) async => null;
```

As generated it moves nothing. Write there what the app keeps under the id of a user. This sketch moves a cart:

```dart title="lib/core/auth/guest_data.dart"
Future<GiveGuestData?> takeGuestData(String guestUid) async {
  final cart = await carts.read(guestUid);
  if (cart.isEmpty) return null;
  return (accountUid) => carts.add(accountUid, cart);
}
```

- `appSession.signIn`, and `appSession.signInWith` for an identity that has an account, call the function before the sign-in, while the guest is still signed in and may read that data. It calls the function that it got back once the user of the account is signed in.
- Only read in `takeGuestData()`: the sign-in may still fail, and then the guest stays. An error thrown there fails the sign-in before it starts.
- An error of the function that it returns is reported as an error of the app, and the user stays signed in.
- Call no method of `appSession` in either function. The sign-in is one of its calls, which run one after another, so the two would wait for each other.
- The function is not called when a guest signs up, since the guest then keeps the id and everything under it. It is not called in an app without anonymous users either.

## An app without the screens

With a module that provides the auth role and without `sign_in`, the app has the session and no guard that reads it. Every screen is open in every mode, `required` too. That includes a screen that a module made for users with an account: `smf create` warns of each such route when it generates the app.

The screens that sign a user in are then yours, and so are the guards. A guard of your own goes into `routeGuards` of `lib/core/router/app_router.dart`, which an app has when one of its modules declares a guard, as [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) does. An app whose modules declare no guard has neither that list nor the code that asks it. This sketch is a gate for a sign-in screen of your own at `/login`, the route `login.login`:

```dart title="lib/core/router/app_router.dart"
  RouteGuard(
    'login.signedIn',
    allows: appSession.allowsApp,
    redirectTo: const LoginLoginLocation(),
    flow: const {'login.login'},
    resumes: false,
  ),
```

It comes after the gates of a first launch, such as that of the onboarding. A guard for the screens that need an account reads `appSession.hasAccount` and names those routes in its `routes`.

## The README and the guide for coding agents

The auth role writes the section "Sign-in" of the README of the app: the mode of the app, what each mode means, that the mode gates nothing on its own, how to change it, and where the data of a guest moves. It also lists the ways to sign in of the app, each with its platforms and what a deletion asks of it, or tells where such a way goes in an app without one, and it says when the app lacks the equivalent that the App Store asks for. `firebase_auth` tells under "Firebase Authentication" how the sign-in methods are enabled, and each module of a way to sign in adds a section of its own, such as "Google sign-in".

The [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app has the section "Authentication" for the session, and with `sign_in` the section "Sign-in" for the screens.

## In tests

The app has one session, and who is signed in outlives a test, into the next test of the same file. So a test signs out first, or expects nothing of who is signed in.

| A test that | Does this |
| --- | --- |
| needs an account before the app starts | It calls `appSession.signUp()` before `bootstrap()`, without awaiting it. A call made before the first start waits for it, and the app then starts with that account. The test makes the call outside the body of a test, as in a `setUpAll`: made in the body of a widget test, it waits in the fake time of that body, and a start that runs in real time never completes. |
| scripts what the provider answers | It gives `appSession.start()` a service of its own, a class of the test that implements `AuthService`. |
| needs another mode | It creates an `AppSessionController` of its own with that mode, and disposes of it. |
| checks what the next launch finds | It runs `initAuth()` again, which creates the service anew, with the user who is signed in, and starts the session with it. |
| brings the user back to the app | It may go through any state of the lifecycle: the session looks only at `AppLifecycleState.resumed`. |

In an app with `sign_in` in the mode `required`, a test that starts the app to look at another screen sees the sign-in unless an account is signed in. The first row is how such a test gets one. [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md#in-tests) has more on tests of the screens and of their state.

A test that runs `bootstrap()` starts the service of the provider, which needs its platform side; see [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md#in-tests).
