Skip to content

docs(auth): update examples to use modular API #8327

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
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
68 changes: 41 additions & 27 deletions docs/auth/multi-factor-auth.md
Original file line number Diff line number Diff line change
@@ -21,8 +21,14 @@ instance for the current user. This is the entry point for most multi-factor
operations:

```js
import auth from '@react-native-firebase/auth';
const multiFactorUser = await auth().multiFactor(auth().currentUser);
import {
PhoneAuthProvider,
PhoneMultiFactorGenerator,
getAuth,
multiFactor,
} from '@react-native-firebase/auth';

const multiFactorUser = await multiFactor(getAuth().currentUser);
```

Request the session identifier and use the phone number obtained from the user
@@ -36,15 +42,15 @@ const phoneOptions = {
};

// Sends a text message to the user
const verificationId = await auth().verifyPhoneNumberForMultiFactor(phoneOptions);
const verificationId = await new PhoneAuthProvider(getAuth()).verifyPhoneNumber(phoneOptions);
```

Once the user has provided the verification code received by text message, you
can complete the process:

```js
const cred = auth.PhoneAuthProvider.credential(verificationId, verificationCode);
const multiFactorAssertion = auth.PhoneMultiFactorGenerator.assertion(cred);
const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
await multiFactorUser.enroll(multiFactorAssertion, 'Optional display name for the user');
```

@@ -58,10 +64,15 @@ default sign-in methods, for example email and password. If the account requires
a second factor to complete login, an exception will be raised:

```js
import auth from '@react-native-firebase/auth';

auth()
.signInWithEmailAndPassword(email, password)
import {
PhoneAuthProvider,
PhoneMultiFactorGenerator,
getAuth,
signInWithEmailAndPassword,
getMultiFactorResolver,
} from '@react-native-firebase/auth';

signInWithEmailAndPassword(getAuth(), email, password)
.then(() => {
// User has not enrolled a second factor
})
@@ -81,7 +92,7 @@ Using the error object you can obtain a
continue the flow:

```js
const resolver = auth().getMultiFactorResolver(error);
const resolver = getMultiFactorResolver(getAuth(), error);
```

The resolver object has all the required information to prompt the user for a
@@ -93,7 +104,7 @@ if (resolver.hints.length > 1) {
}

// Currently only phone based factors are supported
if (resolver.hints[0].factorId === auth.PhoneMultiFactorGenerator.FACTOR_ID) {
if (resolver.hints[0].factorId === PhoneMultiFactorGenerator.FACTOR_ID) {
// Continue with the sign-in flow
}
```
@@ -105,18 +116,18 @@ verification code to the user:
const hint = resolver.hints[0];
const sessionId = resolver.session;

auth()
.verifyPhoneNumberWithMultiFactorInfo(hint, sessionId) // triggers the message to the user
new PhoneAuthProvider(getAuth())
.verifyPhoneNumber(hint, sessionId) // triggers the message to the user
.then(verificationId => setVerificationId(verificationId));
```

Once the user has entered the verification code you can create a multi-factor
assertion and finish the flow:

```js
const credential = auth.PhoneAuthProvider.credential(verificationId, verificationCode);
const credential = PhoneAuthProvider.credential(verificationId, verificationCode);

const multiFactorAssertion = auth.PhoneMultiFactorGenerator.assertion(credential);
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(credential);

resolver.resolveSignIn(multiFactorAssertion).then(userCredential => {
// additionally onAuthStateChanged will be triggered as well
@@ -130,39 +141,42 @@ will trigger with the new authentication state of the user.
To put the example together:

```js
import auth from '@react-native-firebase/auth';

const authInstance = auth();

authInstance
.signInWithEmailAndPassword(email, password)
import {
PhoneAuthProvider,
PhoneMultiFactorGenerator,
getAuth,
signInWithEmailAndPassword,
getMultiFactorResolver,
} from '@react-native-firebase/auth';

signInWithEmailAndPassword(getAuth(), email, password)
.then(() => {
// User has not enrolled a second factor
})
.catch(error => {
const { code } = error;
// Make sure to check if multi factor authentication is required
if (code === 'auth/multi-factor-auth-required') {
const resolver = auth.getMultiFactorResolver(error);
const resolver = getMultiFactorResolver(error);

if (resolver.hints.length > 1) {
// Use resolver.hints to display a list of second factors to the user
}

// Currently only phone based factors are supported
if (resolver.hints[0].factorId === auth.PhoneMultiFactorGenerator.FACTOR_ID) {
if (resolver.hints[0].factorId === PhoneMultiFactorGenerator.FACTOR_ID) {
const hint = resolver.hints[0];
const sessionId = resolver.session;

authInstance
.verifyPhoneNumberWithMultiFactorInfo(hint, sessionId) // triggers the message to the user
new PhoneAuthProvider(getAuth())
.verifyPhoneNumber(hint, sessionId) // triggers the message to the user
.then(verificationId => setVerificationId(verificationId));

// Request verificationCode from user

const credential = auth.PhoneAuthProvider.credential(verificationId, verificationCode);
const credential = PhoneAuthProvider.credential(verificationId, verificationCode);

const multiFactorAssertion = auth.PhoneMultiFactorGenerator.assertion(credential);
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(credential);

resolver.resolveSignIn(multiFactorAssertion).then(userCredential => {
// additionally onAuthStateChanged will be triggered as well
6 changes: 3 additions & 3 deletions docs/auth/oidc-auth.md
Original file line number Diff line number Diff line change
@@ -44,7 +44,7 @@ Before you use `react-native-app-auth` you have to complete the setup in their [
The example below demonstrates how you could setup such a flow within your own application:

```jsx
import auth from '@react-native-firebase/auth';
import { OIDCAuthProvider, getAuth, signInWithCredential } from '@react-native-firebase/auth';
import { authorize } from 'react-native-app-auth';

// using react-native-app-auth to get oauth token from Azure AD
@@ -59,10 +59,10 @@ const config = {
// Log in to get an authentication token
const authState = await authorize(config);

const credential = auth.OIDCAuthProvider.credential(
const credential = OIDCAuthProvider.credential(
'azure_test', // this is the "Provider ID" value from the firebase console
authState.idToken,
);

await auth().signInWithCredential(credential);
await signInWithCredential(getAuth(), credential);
```
44 changes: 28 additions & 16 deletions docs/auth/phone-auth.md
Original file line number Diff line number Diff line change
@@ -56,9 +56,9 @@ a code. Based on whether the code is correct for the device, the method rejects
The example below demonstrates how you could setup such a flow within your own application:

```jsx
import React, { useState, useEffect } from 'react';
import { useState, useEffect } from 'react';
import { Button, TextInput } from 'react-native';
import auth from '@react-native-firebase/auth';
import { getAuth, onAuthStateChanged, signInWithPhoneNumber } from '@react-native-firebase/auth';

function PhoneSignIn() {
// If null, no SMS has been sent
@@ -68,7 +68,7 @@ function PhoneSignIn() {
const [code, setCode] = useState('');

// Handle login
function onAuthStateChanged(user) {
function handleAuthStateChanged(user) {
if (user) {
// Some Android devices can automatically process the verification code (OTP) message, and the user would NOT need to enter the code.
// Actually, if he/she tries to enter it, he/she will get an error message because the code was already used in the background.
@@ -78,13 +78,13 @@ function PhoneSignIn() {
}

useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
const subscriber = onAuthStateChanged(getAuth(), handleAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);

// Handle the button press
async function signInWithPhoneNumber(phoneNumber) {
const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
async function handleSignInWithPhoneNumber(phoneNumber) {
const confirmation = await signInWithPhoneNumber(getAuth(), phoneNumber);
setConfirm(confirmation);
}

@@ -100,7 +100,7 @@ function PhoneSignIn() {
return (
<Button
title="Phone Number Sign In"
onPress={() => signInWithPhoneNumber('+1 650-555-3434')}
onPress={() => handleSignInWithPhoneNumber('+1 650-555-3434')}
/>
);
}
@@ -138,7 +138,13 @@ After successfully creating a user with an email and password (see Authenticatio
```jsx
import React, { useState, useEffect } from 'react';
import { Button, TextInput, Text } from 'react-native';
import auth from '@react-native-firebase/auth';
import {
PhoneAuthProvider,
getAuth,
onAuthStateChanged,
createUserWithEmailAndPassword,
verifyPhoneNumber,
} from '@react-native-firebase/auth';

export default function PhoneVerification() {
// Set an initializing state whilst Firebase connects
@@ -151,20 +157,24 @@ export default function PhoneVerification() {
const [code, setCode] = useState('');

// Handle user state changes
function onAuthStateChanged(user) {
function handleAuthStateChanged(user) {
setUser(user);
if (initializing) setInitializing(false);
}

useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
const subscriber = onAuthStateChanged(getAuth(), handleAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);

// Handle create account button press
async function createAccount() {
try {
await auth().createUserWithEmailAndPassword('jane.doe@example.com', 'SuperSecretPassword!');
await createUserWithEmailAndPassword(
getAuth(),
'jane.doe@example.com',
'SuperSecretPassword!',
);
console.log('User account created & signed in!');
} catch (error) {
if (error.code === 'auth/email-already-in-use') {
@@ -179,16 +189,16 @@ export default function PhoneVerification() {
}

// Handle the verify phone button press
async function verifyPhoneNumber(phoneNumber) {
const confirmation = await auth().verifyPhoneNumber(phoneNumber);
async function handlePhoneNumberVerification(phoneNumber) {
const confirmation = await verifyPhoneNumber(getAuth(), phoneNumber);
setConfirm(confirmation);
}

// Handle confirm code button press
async function confirmCode() {
try {
const credential = auth.PhoneAuthProvider.credential(confirm.verificationId, code);
let userData = await auth().currentUser.linkWithCredential(credential);
const credential = PhoneAuthProvider.credential(confirm.verificationId, code);
let userData = await getAuth().currentUser.linkWithCredential(credential);
setUser(userData.user);
} catch (error) {
if (error.code == 'auth/invalid-verification-code') {
@@ -208,7 +218,9 @@ export default function PhoneVerification() {
return (
<Button
title="Verify Phone Number"
onPress={() => verifyPhoneNumber('ENTER A VALID TESTING OR REAL PHONE NUMBER HERE')}
onPress={() =>
handlePhoneNumberVerification('ENTER A VALID TESTING OR REAL PHONE NUMBER HERE')
}
/>
);
}
Loading
Loading