Skip to content

Commit

Permalink
feat: initial commit of new documentation website (firebase#2925)
Browse files Browse the repository at this point in the history
Co-authored-by: Mike Diarmid <[email protected]>
Co-authored-by: Greg Hesp <[email protected]>
  • Loading branch information
3 people authored Jul 10, 2020
1 parent 2bfa0f6 commit 760c2b4
Show file tree
Hide file tree
Showing 70 changed files with 15,216 additions and 0 deletions.
10 changes: 10 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# editorconfig
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
23 changes: 23 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,26 @@ build/
.settings
/pubspec.yaml
.last_build_id

# Docs

# Dependencies
node_modules

# Production
website/build

# Generated files
.docusaurus
.cache-loader

# Misc
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*

Binary file added docs/_assets/ios-add-files-via-xcode.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/_assets/ios-xcode-copy-items.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions docs/admob/usage.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
title: AdMob
sidebar_label: Usage
---

AdMob usage
6 changes: 6 additions & 0 deletions docs/analytics/usage.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
title: Analytics
sidebar_label: Usage
---

Analytics usage
96 changes: 96 additions & 0 deletions docs/auth/error-handling.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
---
title: Error Handling
sidebar_label: Error Handling
---

The Firebase Authentication SDKs provided a simple way for catching the various errors which may occur which using
authentication methods. FlutterFire exposes these errors via the [`FirebaseAuthException`](!firebase_auth_platform_interface.FirebaseAuthException)
class.

At a minimum, a `code` and `message` are provided, however in some cases additional properties such as an email address
and credential are also provided. For example, if the user is attempting to sign in wih an email and password,
any errors thrown can be explicially caught:

```dart
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: "[email protected]",
password: "SuperSecretPassword!"
);
} catch on FirebaseAuthException (e) {
print('Failed with error code: ${e.code}');
print(e.message);
}
```

Each method provides various error codes and messages depending on the type of authentication invocation type. The
[Reference API](https://pub.dev/documentation/firebase_auth/latest/) provides up-to-date details on the errors for each method.

## Handling `account-exists-with-different-credential` Errors

If you enabled the One account per email address setting in the [Firebase console](https://console.firebase.google.com/project/_/authentication/providers),
when a user tries to sign in a to a provider (such as Google) with an email that already exists for another Firebase user's provider
(such as Facebook), the error `auth/account-exists-with-different-credential` is thrown along with an `AuthCredential` class (Google ID token).
To complete the sign in to the intended provider, the user has to sign first to the existing provider (e.g. Facebook) and then link to the former
`AuthCredential` (Google ID token).

```dart
FirebaseAuth auth = FirebaseAuth.instance;
// Create a credential from a Google Sign-in Request
GoogleAuthCredential googleAuthCredential = GoogleAuthProvider.credential(accessToken: 'xxxx');
try {
// Attempt to sign in the user in with Google
await auth.signInWithCredential(googleAuthCredential);
} catch on FirebaseAuthError (e) {
if (e.code == 'account-exists-with-different-credential') {
// The account already exists with a different credential
String email = e.email;
AuthCredential pendingCredential = e.credential;
// Fetch a list of what sign-in methods exist for the conflicting user
List<String> userSignInMethods = await auth.fetchSignInMethodsForEmail(email);
// If the user has several sign-in methods,
// the first method in the list will be the "recommended" method to use.
if (userSignInMethods.first == 'password') {
// Prompt the user to enter their password
String password = '...';
// Sign the user in to their account with the password
UserCredential userCredential = await auth.signInWithEmailAndPassword(
email: email,
password: password,
);
// Link the pending credential with the existing account
await userCredential.user.linkWithCredential(pendingCredential);
// Success! Go back to your application flow
return goToApplication();
}
// Since other providers are now external, you must now sign the user in with another
// auth provider, such as Facebook.
if (userSignInMethods.first == 'facebook.com') {
// Create a new Facebook credential
String accessToken = await triggerFacebookAuthentication();
FacebookAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(accessToken);
// Sign the user in with the credential
UserCredential userCredential = await auth.signInWithCredential(facebookAuthCredential);
// Link the pending credential with the existing account
await userCredential.user.linkWithCredential(pendingCredential);
// Success! Go back to your application flow
return goToApplication();
}
// Handle other OAuth providers...
}
}
```


64 changes: 64 additions & 0 deletions docs/auth/overview.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
title: Authentication
sidebar_label: Overview
---

## What does it do?

Firebase Authentication provides backend services & easy-to-use SDKs to authenticate users to your app.
It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook
and Twitter, and more.

<YouTube id="8sGY55yxicA" />

## Installation

Before installing the Authentication plugin, ensure that you have followed the [Getting Started](../overview.mdx) documentation
and have initialized FlutterFire.

### 1. Add dependency

Add the [`firebase_auth`](https://pub.dartlang.org/packages/firebase_auth) dependency to your projects `pubspec.yaml` file:

```yaml {5} title="pubspec.yaml"
dependencies:
flutter:
sdk: flutter
firebase_core: "{{ plugins.firebase_core }}"
firebase_auth: "{{ plugins.firebase_auth }}"
```
### 2. Download dependency
Download the dependency by running the following command in your project:
```bash
$ flutter pub get
```

### 3. (Web Only) Add the SDK

If using FlutterFire on the web, add the [`firebase-auth`](!firebase_auth) JavaScript SDK to your `index.html` file:

```html {5} title="web/index.html"
<html>
...
<body>
<script src="https://www.gstatic.com/firebasejs/{{ web.firebase_cdn }}/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/{{ web.firebase_cdn }}/firebase-auth.js"></script>
</body>
</html>
```

### 4. Rebuild your app

Once complete, rebuild your Flutter application:

```bash
$ flutter run
```

## Next Steps

Once installed, you're ready to start using Firebase Authentication in your Flutter Project. View the
[Usage documentation](usage.mdx) to get started.
168 changes: 168 additions & 0 deletions docs/auth/phone.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
---
title: Phone Authentication
sidebar_label: Phone Auth
---

Phone authentication allows users to sign in to Firebase using their phone as the authenticator. An SMS message is sent
to the user (using the provided phone number) containing a unique code. Once the code has been authorized, the user is able to sign
into Firebase.

> Phone numbers that end users provide for authentication will be sent and stored by Google to improve spam and abuse
> prevention across Google service, including to, but not limited to Firebase. Developers should ensure they have the
> appropriate end-user conset prior to using the Firebase Authentication phone number sign-in service.authentication
Firebase Phone Authentication is not supported in all countries. Please see their [FAQs](https://firebase.google.com/support/faq/#develop) for more information

## Setup

Before starting with Phone Authentication, ensure you have followed these steps:

1. Enable Phone as a Sign-In method in the [Firebase console](https://console.firebase.google.com/u/0/project/_/authentication/providers).
2. **Android**: If you haven't already set your app's SHA-1 hash in the [Firebase console](https://console.firebase.google.com/), do so.
See [Authenticating Your Client](https://developers.google.com/android/guides/client-auth) for information about finding your app's SHA-1 hash.
3. **iOS**: In XCode, [enable push notifications](http://help.apple.com/xcode/mac/current/#/devdfd3d04a1) for your project & ensure
your APNs authentication key is [configured with Firebase Cloud Messaging (FCM)](https://firebase.google.com/docs/cloud-messaging/ios/certs).
To view an indepth explaination of this step, view the [Firebase iOS Phone Auth](https://firebase.google.com/docs/auth/ios/phone-auth) documentation.
4. **Web**: Ensure that you have added your applications domian on the [Firebase console](https://console.firebase.google.com/), under
**OAuth redirect domains**.

**Note**; Phone number sign-in is only available for use on real devices and the web. To test your authentication flow on device emulators,
please see [Testing](#testing).

## Usage

FlutterFire provides two individual ways to sign a user in with their phone number. Native (e.g. Android & iOS) platforms provide
different functionality to validating a phone number than the web, therefore two methods exist for each platform exclusively:

- **Native Platform**: [`verifyPhoneNumber`](!firebase_auth.FirebaseAuth.verifyPhoneNumber).
- **Web Platform**: [`signInWithPhoneNumber`](!firebase_auth.FirebaseAuth.signInWithPhoneNumber).

### Native: `verifyPhoneNumber`

On native platforms, the users phone number must be first verified and then the user can either sign-in or link their account with a
[`PhoneAuthCredential`](!firebase_auth_platform_interface.PhoneAuthCredential).

First you must prompt the user for their phone number. Once provided, call the `verifyPhoneNumber()` method:

```dart
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: '+44 7123 123 456',
verificationCompleted: (PhoneAuthCredential credential) {},
verificationFailed: (FirebaseAuthException e) {},
codeSent: (String verificationId, int resendToken) {},
codeAutoRetrievalTimeout: (String verificationId) {},
);
```

There are 4 seperate callbacks that you must handle, each will determine how you update the application UI:

1. **[verificationCompleted](#verificationCompleted)**: Automatic handling of the SMS code on Android devices.
2. **[verificationFailed](#verificationFailed)**: Handle failure events such as invalid phone numbers or whethehr the SMS quota has been exceeded.
3. **[codeSent](#codeSent)**: Handle when a code has been sent to the device from Firebase, used to prompt users to enter the code.
4. **[codeAutoRetrievalTimeout](#codeAutoRetrievalTimeout)**: Handle a timeout of when automatic SMS code handling fails.

#### verificationCompleted

This handler will only be called on Android devices which support automatic SMS code resolution.

When the SMS code is delivered to the device Android will automatically verify the SMS code without
requiring the user to manually input the code. If this event occurs, a `PhoneAuthCredential` is automatically provided which can be
used to sign-in with or link the users phone number.

```dart
FirebaseAuth auth = FirebaseAuth.instance;
await auth.verifyPhoneNumber(
phoneNumber: '+44 7123 123 456',
verificationCompleted: (PhoneAuthCredential credential) async {
// ANDROID ONLY!
// Sign the user in (or link) with the auto-generated credential
await auth.signInWithCredential(credential);
},
);
```

#### verificationFailed

If Firebase returns an error, for example for an incorrect phone number or if the SMS quota for the project has exceeded,
a `FirebaseAuthException` will be sent to this handler. In this case, you would prompt your user something went wrong depending on the error
code.

```dart
FirebaseAuth auth = FirebaseAuth.instance;
await auth.verifyPhoneNumber(
phoneNumber: '+44 7123 123 456',
verificationFailed: (FirebaseAuthException e) {
if (e.code == 'invalid-phone-number') {
print('The provided phone number is not valid.');
}
// Handle other errors
},
);
```

#### codeSent

When Firebase sends an SMS code to the device, this handler is triggered with a `verificationId` and `resendToken`.

Once triggered, it would be a good time to update your application UI to prompt the user to enter the SMS code they're expecting.
Once the SMS code has been entered, you can combine the verification ID with the SMS code to create a new `PhoneAuthCredential`:

```dart
FirebaseAuth auth = FirebaseAuth.instance;
await auth.verifyPhoneNumber(
phoneNumber: '+44 7123 123 456',
codeSent: (String verificationId, int resendToken) async {
// Update the UI - wait for the user to enter the SMS code
String smsCode = 'xxxx';
// Create a PhoneAuthCredential with the code
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.credential(verificationId, smsCode);
// Sign the user in (or link) with the credential
await auth.signInWithCredential(phoneAuthCredential);
},
);
```

By default, Firebase will not re-send a new SMS message if it has been recently sent. You can however override this behaviour
by re-calling the `verifyPhoneNumber` method with the resend token to the `forceResendingToken` argument.
If successful, the SMS message will be resent.

#### codeAutoRetrievalTimeout

On Android devices which support automatic SMS code resolution, this handler will be called if the device has not automatically
resolved an SMS message within a certain timeframe. Once the timeframe has passed, the device will no longer attempt to resolve
any incoming messages.

By default, the device waits for 30 seconds however this can be customized with the `timeout` argument:

```dart
FirebaseAuth auth = FirebaseAuth.instance;
await auth.verifyPhoneNumber(
phoneNumber: '+44 7123 123 456',
timeout: const Duration(seconds: 60),
codeAutoRetrievalTimeout: (String verificationId) {
// Auto-resolution timed out...
},
);
```

### Web: `signInWithPhoneNumber`

TODO

## Testing

Firebase provides support for locally testing phone numbers:

1. On the Firebase Console, select the "Phone" authentication provider and click on the "Phone numbers for testing" dropdown.
2. Enter a new phone number (e.g. `+44 7444 555666`) and a test code (e.g. `123456`).

If providing a test phone number to either the `verifyPhoneNumber` or `signInWithPhoneNumber` methods, no SMS will actually be sent. You
can instead provide the test code directly to the `PhoneAuthProvider` or with `signInWithPhoneNumber`s confirmation result handler.
Loading

0 comments on commit 760c2b4

Please sign in to comment.