Skip to content
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

(DOCSP-33534) Add authentication hooks to React Native docs #3037

Merged
merged 37 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from 33 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
972764f
Establish component bases
krollins-mdb Sep 30, 2023
7d0c328
Add email/password example
krollins-mdb Oct 2, 2023
afe46c3
Add basic table for useEmailPasswordAuth
krollins-mdb Oct 2, 2023
89401bb
Add login and register example for email/pass
krollins-mdb Oct 2, 2023
41e9089
Merge branch 'master' into DOCSP-27838
krollins-mdb Oct 2, 2023
b7c0cb3
Get link identities component and test workign
krollins-mdb Oct 4, 2023
5e80426
- Update realm and realm/react deps
krollins-mdb Oct 6, 2023
23d6e55
- Refactor to use `result`
krollins-mdb Oct 6, 2023
3a68ae4
- Generate samples
krollins-mdb Oct 10, 2023
d032cb6
Try code-block
krollins-mdb Oct 10, 2023
0ef8a95
Actually add directive
krollins-mdb Oct 10, 2023
e72727b
Try 2 columns
krollins-mdb Oct 10, 2023
9ba558c
Add remaining hook method examples
krollins-mdb Oct 10, 2023
b72a524
Lots of content updates
krollins-mdb Oct 10, 2023
2defb1e
- Add reset password example
krollins-mdb Oct 11, 2023
4622717
Content clean up
krollins-mdb Oct 11, 2023
2238a26
Merge branch 'master' into DOCSP-27838
krollins-mdb Oct 11, 2023
18d1d76
A bit more content clean up
krollins-mdb Oct 11, 2023
eb3e8b5
Fix typo
krollins-mdb Oct 11, 2023
78038eb
- Generate updated snippets
krollins-mdb Oct 11, 2023
f19519f
Link identities updates
krollins-mdb Oct 11, 2023
06336cf
Add useAuth reference table
krollins-mdb Oct 11, 2023
69e2be6
Update configure user auth section
krollins-mdb Oct 11, 2023
d4b4995
Add missing back ticks
krollins-mdb Oct 12, 2023
d0b2e17
Merge branch 'mongodb:master' into DOCSP-27838
krollins-mdb Oct 12, 2023
a2cc38f
- Add fallback component section
krollins-mdb Oct 16, 2023
4380cc2
Regenerate snippets
krollins-mdb Oct 16, 2023
a3f4172
Minor updates
krollins-mdb Oct 16, 2023
0a10ace
Remove examples from ordered list
krollins-mdb Oct 16, 2023
f9f43e6
Revert unintended changes
krollins-mdb Oct 16, 2023
3aa3df7
Update inline code blocks
krollins-mdb Oct 17, 2023
980fccb
Implement more feedback from
krollins-mdb Oct 17, 2023
6d78eb6
Merge branch 'master' into DOCSP-27838
krollins-mdb Oct 17, 2023
8df9e9d
Apply suggestions from code review
krollins-mdb Oct 17, 2023
a6b441c
Implement Cory's feedback
krollins-mdb Oct 17, 2023
835965f
- eslint and prettier config to one prop per line
krollins-mdb Oct 17, 2023
7aa2f64
Simplify anonymous sample
krollins-mdb Oct 18, 2023
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
2 changes: 2 additions & 0 deletions examples/react-native/v12/TestApp/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {CompensatingWriteErrorHandling} from './src/components/errors/Compensati

// Screens
import {SubscriptionScreen} from './src/screens/SubscriptionScreen';
import {AuthenticationScreen} from './src/screens/AuthenticationScreen';

// Types
import {RootStackParamList} from './src/navigation/types';
Expand Down Expand Up @@ -48,6 +49,7 @@ function App(): JSX.Element {
name="Errors"
component={CompensatingWriteErrorHandling}
/>
<Drawer.Screen name="Authentication" component={AuthenticationScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
Expand Down
4 changes: 2 additions & 2 deletions examples/react-native/v12/TestApp/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions examples/react-native/v12/TestApp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@
"@react-navigation/native": "^6.1.7",
"@react-navigation/native-stack": "^6.9.13",
"@react-navigation/stack": "^6.3.17",
"@realm/react": "^0.6.0",
"@realm/react": "^0.6.1",
"react": "18.2.0",
"react-native": "^0.72",
"react-native-gesture-handler": "^2.12.1",
"react-native-get-random-values": "^1.9.0",
"react-native-reanimated": "^3.4.2",
"react-native-safe-area-context": "^4.7.1",
"react-native-screens": "^3.24.0",
"realm": "^12"
"realm": "^12.2.1"
},
"devDependencies": {
"@babel/core": "^7.20.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import 'react-native';
import React from 'react';
import {BSON} from 'realm';
import {LinkIdentities} from './LinkIdentities';
import {render, screen, userEvent, within} from '@testing-library/react-native';

test('linking an anonymous user with an email/password account', async () => {
render(<LinkIdentities />);

const user = userEvent.setup();
const userEmail = `${new BSON.UUID()}@example.com`;
const userPassword = 'v3ryv3rySECRET';

// Log in anonymous user in the fallback "Login" component.
const loginButton = await screen.findByTestId('log-in');
await user.press(loginButton);

// LinkIdentities component should render.
const emailInput = await screen.findByTestId('email-input');
const passwordInput = await screen.findByTestId('password-input');
const registerButton = await screen.findByTestId('register-and-link');
const deleteUser = await screen.findByTestId('delete-user');

const userIdentityList = await screen.findByTestId('list-container');
const userIdentityNodes = await within(userIdentityList).findAllByTestId(
'user-identity',
);

// There should only be one identity: the anonymous login.
expect(userIdentityNodes.length).toEqual(1);

// Register user and link anonymous id with
// email and password account.
await user.type(emailInput, userEmail);
await user.type(passwordInput, userPassword);
await user.press(registerButton);

// Use promise hack to wait for app services to
// finish linking identities.
await new Promise(r => setTimeout(r, 1000));

const updatedUserIdentityList = await screen.findByTestId('list-container');
const updatedUserIdentityNodes = await within(
updatedUserIdentityList,
).findAllByTestId('user-identity');

// There should only be two identities: anonymous and email/password.
expect(updatedUserIdentityNodes.length).toEqual(2);

// Delete user
await user.press(deleteUser);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
// :snippet-start: imports
import React, {useEffect, useState} from 'react';
import {FlatList, StyleSheet, Text, TextInput, View} from 'react-native';
import {Credentials} from 'realm';
import {
AppProvider,
UserProvider,
useApp,
useUser,
useAuth,
useEmailPasswordAuth,
AuthOperationName,
} from '@realm/react';

// A custom wrapper around <Pressable> for styling
import {Button} from '../../utility-components/Button';
// :snippet-end:
import {APP_ID} from '../../../../appServicesConfig'; // :remove:
krollins-mdb marked this conversation as resolved.
Show resolved Hide resolved

// :snippet-start: providers
export const LinkIdentities = () => {
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
<RegisterUser />
</UserProvider>
</AppProvider>
);
};

// :replace-start: {
// "terms": {
// "testID=\"log-in\"": ""
// }
// }
// Log in an anonymous user. This component only mounts
// if there is no authenticated user.
const LogIn = () => {
const {logInWithAnonymous} = useAuth();

return (
<View>
<Text>No one is logged in yet.</Text>
<Button testID="log-in" title="Log in" onPress={logInWithAnonymous} />
</View>
);
};
// :replace-end:
// :snippet-end:

// :snippet-start: user-identities
type UserIdentity = {
providerType: string;
id: string;
};

// Link an anonymous user to an email/password identity.
// For this example, the App Services backend automatically
// confirms users' emails.
const RegisterUser = () => {
const app = useApp();
const user = useUser();
const {logOut} = useAuth();
const {register, result} = useEmailPasswordAuth();

const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [userIdentities, setUserIdentities] = useState(user.identities);
// :remove-start:
// This useEffect is for test purposes only. If the current
// user has more than 1 identity, then log them out. We need
// an unlinked user for this test. Only runs once when the
// component is first mounted.
useEffect(() => {
if (userIdentities.length > 1) {
logOut();
}
}, []);
// :remove-end:

// Use `result` to react to successful registration
// by linking credentials with the current user.
useEffect(() => {
if (result.operation === AuthOperationName.Register && result.success) {
linkCredentials();
}
}, [result]);

if (!userIdentities.length) {
setUserIdentities(user.identities);
}

const linkCredentials = async () => {
const credentials = Credentials.emailPassword(email, password);
await user.linkCredentials(credentials); // :emphasize:

setUserIdentities(user.identities);
};

const registerAndLinkIdentities = async () => {
register({email, password});
};

const deleteUser = async () => {
app.deleteUser(app.currentUser!);
};

// :replace-start: {
// "terms": {
// "style={styles.section": "",
// "style={styles.inputGroup": "",
// "style={styles.buttonGroup}": "",
// "testID=\"user-identity\"": ""
// }
// }
return (
<View style={styles.section}>
{/* Show all identities associated with the current user */}
<FlatList
testID="list-container" // :remove:
data={userIdentities}
renderItem={({item}) => (
<Text testID="user-identity">ID: {item.id}</Text>
)}
keyExtractor={item => item.id}
/>

<Text>Link anonymous user with email/password account</Text>
<View style={styles.inputGroup}>
<TextInput
testID="email-input" // :remove:
style={styles.textInput} // :remove:
onChangeText={setEmail}
value={email}
placeholder="email..."
/>
<TextInput
testID="password-input" // :remove:
style={styles.textInput} // :remove:
onChangeText={setPassword}
value={password}
placeholder="password..."
/>
</View>

<View style={styles.buttonGroup}>
<Button
testID="register-and-link" // :remove:
title="Register"
onPress={registerAndLinkIdentities}
/>
<Button
testID="log-out" // :remove:
title="Log out"
onPress={logOut}
/>
<Button
testID="delete-user" // :remove:
title="Delete user"
onPress={deleteUser}
/>
</View>
</View>
);
// :replace-end:
};
// :snippet-end:

const styles = StyleSheet.create({
section: {
flex: 1,
marginTop: 8,
paddingVertical: 12,
alignItems: 'center',
},
textInput: {
backgroundColor: '#C5CAE9',
borderBottomWidth: StyleSheet.hairlineWidth,
marginVertical: 5,
},
inputGroup: {
width: '100%',
},
buttonGroup: {
flexDirection: 'row',
flexWrap: 'wrap',
marginVertical: 12,
paddingVertical: 8,
justifyContent: 'center',
alignItems: 'center',
},
});
Loading
Loading