# `firebase_auth`

| Package | Kind | Provides the role | Needs | Choose with |
| --- | --- | --- | --- | --- |
| [`smf_firebase_auth`](https://pub.dev/packages/smf_firebase_auth) | infrastructure | Authentication | [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md) | `-m firebase_auth` |

`firebase_auth` signs the users of the app in with [Firebase Authentication](https://firebase.google.com/docs/auth), through the [firebase_auth](https://pub.dev/packages/firebase_auth) package: with an email address and a password, as anonymous users, and with the credentials of the ways to sign in of Google and Apple that [`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) add.

The module brings the service and no screens. The screens of sign-in are the feature [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), which requires a module such as this one. The code of the app signs in, up and out through `appSession`, which the auth role generates; see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md).

## What it adds to the app

| In the app | What it is |
| --- | --- |
| `firebase_auth: ^6.7.0` in the dependencies | The package of Firebase Authentication. |
| `lib/core/auth/firebase_auth_service.dart` | `FirebaseAuthService`, the sign-in service of the app on `FirebaseAuth.instance`. |
| `tool/enable_firebase_sign_in.dart` | The script that enables the ways to sign in in the Firebase project, and sets up what Google needs. |
| The section "Firebase Authentication" of the README | How the ways to sign in are enabled, with the script and in the Firebase console, and in an app with Google or Apple what the script sets up for them and what is left to you. |
| Steps by hand, in an app with Apple or Google | What no command sets up for these ways to sign in; see [Google and Apple](#google-and-apple). |

Whichever module provides it, the auth role adds four files in `lib/core/auth/`:

| File | What it holds |
| --- | --- |
| `app_session.dart` | `appSession`, which tells who uses the app and through which code signs in, up and out, `authMode`, the mode of the app, and `initAuth()`. |
| `auth_service.dart` | `AuthService`, the interface that this module implements, and `AuthFailure` with its reasons. |
| `guest_data.dart` | `takeGuestData()`, which you edit: what an anonymous user has when they sign in to an account that exists already. |
| `sign_in_methods.dart` | `appSignInMethods`, the ways to sign in with an identity provider of the app, such as Google; see [ways to sign in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in). |

In its platform phase, `bootstrap()` initializes Firebase and then starts the session. This is `bootstrap()` of an app with this module alone:

```dart title="lib/bootstrap.dart"
Future<void> bootstrap() async {
  await Firebase.initializeApp(options: firebaseOptionsOfFlavor);
  await initAuth();
}
```

Firebase keeps the user on the device and hands that user over when it is initialized. So the service is created without waiting and has the user at once, and the app knows who is signed in before its first frame.

In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the auth role describes the session under "Authentication". The module adds which file is on Firebase Authentication, where a code of Firebase gets its reason, that the ways to sign in are enabled in the Firebase project, and that an agent runs the script that enables them only when asked. In an app with Google, it adds what the script does for Google, and with Apple, that Apple is enabled in the Firebase console with a private key that never goes into the app.

## Enable the ways to sign in

The ways to sign in are enabled in the Firebase project, not in the code:

- Email/Password, in every mode of the app;
- Anonymous, when the [mode](https://doc.saymyframe.com/guides/sign-in.md#the-mode) of the app is `anonymous`;
- Google and Apple, for the [ways to sign in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in) of the app.

The script of the app enables those of them that the app needs, all of them except Apple, with the [Firebase CLI](https://firebase.google.com/docs/cli) 15.34.0 or later:

```bash
dart tool/enable_firebase_sign_in.dart
```

In a terminal, `smf create` offers to run it right after `dart tool/configure_firebase.dart dev` configured the app. The question has a notice of what the script does for a way to sign in of Google, which changes the Firebase project and files of the app. A step cannot tell which ways to sign in the app has, so the question is the same in every app. The Firebase console enables the methods without the script, under [Authentication > Sign-in method](https://console.firebase.google.com/project/_/authentication/providers) of the project that the app is configured for.

The script reads the project from `firebase.json` and the mode from `authMode` of the app, and never disables a method. It changes no file of the app but those that Google needs. A run covers one project, so where flavors have projects of their own, run it with `--project <id>` for each. Run it again after you changed the mode to `anonymous`. [Firebase](https://doc.saymyframe.com/guides/firebase.md#sign-in-methods-of-firebase-authentication) describes the question, what the script does and its arguments, such as `--project <id>` and `--account <email>`.

Until the ways to sign in are enabled, signing in and signing up fail with the reason `notConfigured`, and the `developerHint` of the failure tells both ways:

```text
AuthFailure: notConfigured (Sign-in is not enabled in the Firebase project my-project (Firebase answered operation-not-allowed). To fix it, run `dart tool/enable_firebase_sign_in.dart` in the directory of the app, or enable Email/Password, and Anonymous for an app that signs in anonymous users, in the Firebase console under Authentication > Sign-in method: https://console.firebase.google.com/project/my-project/authentication/providers)
```

In the mode `anonymous`, the app also starts without a user until Anonymous is enabled.

Before it generates the app, SMF checks the machine for a Firebase CLI that enables the methods without adding a web app to the project, as "Firebase CLI 15.34.0 or later". The check only warns. With an older Firebase CLI, the run tells how to update it and prints the command of the script for later. The script asks the Firebase CLI for its version too, and stops with what to do when it is older.

## Google and Apple

The service takes the credentials of the ways to sign in of Google and Apple. `signInWith` and `linkWith` give Firebase a credential of Google with its ID token, and one of Apple with its ID token, its raw nonce and the name of the user. `AuthUser.issuers`, and so `AccountSession.issuers`, comes from the identities that Firebase lists for the user.

The `validate` hook of the provider reports a way to sign in of another identity provider, since Firebase would not take its credential, and a way to sign in whose needs the script cannot set up for its identity provider. The problem names the module of that way to sign in, so `smf create` leaves that module out of the app with a warning and generates the rest, and with `--strict` it stops instead; see [lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict).

| What the service does | Why |
| --- | --- |
| When Firebase refuses to link a credential, because its identity or its email address belongs to another user, the service keeps what Firebase gave back for that credential object, and a sign-in with the identical object uses it once. A credential of Apple can be taken only once. | `appSession` signs in to the account that has the identity with the same object. |
| A link that Firebase refuses fails with `credentialInUse` for an identity that another user has, and with `accountExistsWithOtherMethod` for an email address that has an account. | The same codes of Firebase mean `emailInUse` for a link with a password. |
| `deleteAccount` with a fresh credential signs the user in again with it, then revokes the tokens of Apple with the authorization code of the credential, on iOS and macOS, and then deletes the user and signs out. A credential of Google revokes nothing. | The App Store asks an app with Sign in with Apple to revoke its tokens when the user deletes the account. |
| A revocation that fails keeps the account and fails with `notConfigured`, unless the answer is no matter of the setup: no network, too many attempts, a disabled user, or a session that has ended. | Firebase revokes the tokens of Apple with the key of Apple that you set in the console, and a missing key is a mistake of the setup. |
| A confirmation with the credential of another user fails with `invalidCredentials`, and so does one of an identity that has no user. For the latter the service reloads the user first: a user whom the server deleted is signed out, and the call fails with `recentSignInRequired`. | Firebase answers the first with `user-mismatch` and the second with `user-not-found`, which for another call means a session that has ended. |
| A credential of Apple without a raw nonce, and on iOS and macOS a fresh one without an authorization code, fails with `notConfigured` before Firebase is asked. | Firebase needs the nonce, and a deletion without the code would skip the revocation. |

Google needs more of the Firebase project than an enabled method: the SHA of the keys of the Android app, its clients in the Firebase files of the app, and the URL scheme of the iOS app. The script of the app sets these up for the project that `firebase.json` names, and gives Google the name of the app and the email address of the account of the Firebase CLI for its consent screen. The SHA of a release, of the upload key and of the app signing key of Google Play, is yours to add. No command of the Firebase CLI enables Apple, so the script tells what to set in the Firebase console, where the deletion of an account that signs in with Apple also needs the Services ID and the key of Apple. [Firebase](https://doc.saymyframe.com/guides/firebase.md#google) has each step.

What no command does, the module lists among the steps by hand of the app, by its ways to sign in: `firebase_auth.apple_provider` and `firebase_auth.apple_revocation` for Apple, and `firebase_auth.google_release_sha` for a way to sign in that needs the certificate of the Android app, such as Google. The README of the app lists them under "Finish the setup", and the run ends with the link to their guide. The click-by-click guides show each screen: [the Apple provider](https://doc.saymyframe.com/setup/firebase-auth-apple-provider.md), [the Apple key](https://doc.saymyframe.com/setup/firebase-auth-apple-revocation.md) and [the SHA of a release](https://doc.saymyframe.com/setup/firebase-auth-google-release-sha.md).

Until a way to sign in is enabled, signing in with it fails with `notConfigured`. The hint names the way, and for Google the script too:

```text
AuthFailure: notConfigured (Sign-in with Google is not enabled in the Firebase project my-project (Firebase answered operation-not-allowed). To fix it, run `dart tool/enable_firebase_sign_in.dart` in the directory of the app, or enable Google in the Firebase console under Authentication > Sign-in method: https://console.firebase.google.com/project/my-project/authentication/providers)
```

## The reasons of a failure

A call of `appSession` fails only with an `AuthFailure`, whose `reason` the app shows a text for. The service gives each code of Firebase its reason, in `_failureOf()` of its file:

| Reason | Codes of Firebase |
| --- | --- |
| `invalidCredentials` | `invalid-credential`, `invalid-login-credentials`, `wrong-password`, `user-not-found`, `missing-or-invalid-nonce`, `user-mismatch` |
| `emailInUse` | `email-already-in-use` and `credential-already-in-use`, outside a link of a credential |
| `credentialInUse` | `credential-already-in-use` in a link of a credential |
| `accountExistsWithOtherMethod` | `account-exists-with-different-credential`, and `email-already-in-use` in a link of a credential |
| `weakPassword` | `weak-password`, `password-does-not-meet-requirements` |
| `invalidEmail` | `invalid-email`, `missing-email` |
| `userDisabled` | `user-disabled` |
| `tooManyAttempts` | `too-many-requests` |
| `network` | `network-request-failed` |
| `recentSignInRequired` | `requires-recent-login` |
| `notConfigured` | `operation-not-allowed`, `admin-restricted-operation`, and any code whose message has `CONFIGURATION_NOT_FOUND` |
| `unknown` | Any other code. The `developerHint` has the code and the message of Firebase on one line. |

Two cases need more than the code:

- Firebase tells of a project in which Authentication was never set up only in a message: that of an unknown error on Android, and that of an internal error on iOS, where the message is the description of the error over many lines. The service finds `CONFIGURATION_NOT_FOUND` there and answers `notConfigured`. The hint names the code and `CONFIGURATION_NOT_FOUND`, and leaves the description out.
- On iOS and macOS, Firebase may answer for such a project with an internal error whose message says no more. Nothing tells it from another internal error, so the service answers `notConfigured` there too, with a hint that says that it may be another error.

A code that the service does not know becomes `unknown`. To give it a reason, add it to `_failureOf()`.

## What the service adds to the package

The auth role promises more than the package does in a few places, and the service makes up the difference:

| What the service does | Why |
| --- | --- |
| An empty address or password fails before Firebase is asked. An empty address is `invalidEmail`. An empty password is `invalidCredentials` in a sign-in, and `weakPassword` in a sign-up. | Android refuses an empty text with a code that has no reason, and iOS answers an empty password as a wrong one. |
| A user has no address when Firebase has an empty one. | Android has an empty address, not none, for an anonymous user whom it kept on the device. |
| It signs out after it deleted a user. | The package keeps a deleted user as its current one until the platform tells it of the sign-out. |
| A call for the user who is signed in, such as the deletion of the account, signs that user out first when the session of the user has ended on the server, and fails with `recentSignInRequired`. Firebase answers such a call with `user-token-expired`, `invalid-user-token`, `user-not-found` or `no-current-user`. | A session ends on the server when the account is deleted, or its password changed, on another device. |
| A password reset completes when Firebase answers `user-not-found`. | A project without the protection against the enumeration of email addresses tells that an address has no account, and the app should not. |
| It tells of the user after each of its calls and when Firebase tells of a change, each time with the user that it has when a listener hears of it. | A listener then never hears of a user who is not the current one any more. |

The service is the same in every mode of the app.

## The message of a password reset

Firebase sends the message with which a user sets a new password from a template of the project: [Authentication > Templates](https://console.firebase.google.com/project/_/authentication/emails) in the Firebase console.

The module uses the localization role. In an app with it, the service gives Firebase the language that the app is in before it asks for the message: the language that the user chose, or the one that the device prefers among those of the app.

```dart title="lib/core/auth/firebase_auth_service.dart"
    // The message is in the language that the app is in.
    await _auth.setLanguageCode(
      (appLocale.value ??
              basicLocaleListResolution(
                WidgetsBinding.instance.platformDispatcher.locales,
                appLocales,
              ))
          .languageCode,
    );
```

In an app without the role, the service sets no language.

## Anonymous users

In the mode `anonymous`, the app signs in an anonymous user when it starts, and signing up gives that same user the account. While an anonymous user is signed in, Firebase answers a further anonymous sign-in with that user and creates no other.

When an anonymous user signs in to an account that exists already, the anonymous user stays in the Firebase project, and nobody can sign in as that user again. A project that is upgraded to Firebase Authentication with Identity Platform can delete anonymous users that are older than 30 days automatically; see [Automatic clean-up](https://firebase.google.com/docs/auth/android/anonymous-auth#auto-cleanup) in the documentation of Firebase. What the app itself keeps under the id of the anonymous user moves as `takeGuestData()` says; see [the data of a guest](https://doc.saymyframe.com/guides/sign-in.md#the-data-of-a-guest).

## In tests

A test that runs `main()` or `bootstrap()` starts Firebase with the options of the flavor of the test, `dev`, which needs a mock of its platform side, and the firebase_auth plugin brings no mock of its own platform side for tests. A test of a screen needs neither: it gives `appSession.start()` a service of its own; see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#in-tests).

SMF's CI checks the service on the real firebase_auth package, over a stand-in for its platform side that answers the messages of the plugin: what each call sends to Firebase, the reason for each code as Android and iOS send it, and the user whom a start finds on the device. The stand-in takes the test tokens of the ways to sign in of Google and Apple, takes a token with a nonce once, and answers a refused link with a credential of its own, so the test of the ways to sign in of the auth role runs on this module too. On devices it checks that the session of the app has the user that the plugin has. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time).

## Choosing it

`smf create` asks which module provides the authentication of the app, and offers None as well. With a provider chosen, it then asks who may use the app without an account. To choose both without the questions:

```bash
smf create my_app -m firebase_auth --auth-mode guest
```

`firebase_core` comes with the module:

```text
Adding firebase_core: a dependency of firebase_auth.
Adding flutter_core: the only provider of the app entry role, which every app needs.
```

The feature [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) requires the role that this module provides, so `-m sign_in` brings the module too while it is the only one that provides sign-in.

After generation, `firebase_core` asks whether to configure the flavor `dev`, as for every app with Firebase, and this module then asks whether to enable the ways to sign in; see [Firebase](https://doc.saymyframe.com/guides/firebase.md).

[`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) require the role too, so each brings this module while it is the only one that provides sign-in.
