Docs Menu

Docs HomeDevelop ApplicationsAtlas Device SDK

Manage Email/Password Users - React Native SDK

On this page

  • Prerequisites
  • Configure User Authentication in Client
  • Set up @realm/react Providers
  • Log In with a Fallback Component
  • Register a New User Account
  • Confirm a User's Email Address
  • Retry User Confirmation Methods
  • Resend a Confirmation Email
  • Retry a User Confirmation Function
  • Reset a User's Password
  • Reset Password with Email
  • Call a Password Reset Function
  • useEmailPasswordAuth Hook Reference

You can register a new user account, confirm a user email address, or reset a user's password in your app's React Native client code.

The @realm/react hook useEmailPasswordAuth has methods and enums specifically for managing email/password users. Refer to useEmailPasswordAuth Hook for a quick reference.

Before you can authenticate a user, you must:

@realm/react has providers and hooks for user authentication. To configure user authentication:

  1. Set up @realm/react providers.

  2. Log a user in with a UserProvider fallback component.

Components wrapped by AppProvider can access the useApp and useAuth hooks. These components only render if AppProvider successfully connects to your App Services backend.

Components wrapped by UserProvider can access authenticated users with the useUser hook. These components only render if your app has an authenticated user

To configure user authentication:

  1. Wrap all components that need to access App Services in AppProvider.

  2. Inside of AppProvider, wrap all components that you want to have access to an authenticated user with UserProvider.

  3. In UserProvider, include a fallback prop with a component that logs a user in. The app renders this component if there is no authenticated user.

import React from 'react';
import {AppProvider, UserProvider} from '@realm/react';
// Fallback log in component that's defined in another file.
import {LogIn} from './Login';
export const LoginExample = () => {
return (
<ScrollView>
<AppProvider id={APP_ID}>
{/* If there is no authenticated user, mount the
`fallback` component. When user successfully
authenticates, the app unmounts the `fallback`
component (in this case, the `LogIn` component). */}
<UserProvider fallback={LogIn}>
{/* Components inside UserProvider have access
to the user. These components only mount if
there's an authenticated user. */}
<UserInformation />
</UserProvider>
</AppProvider>
</ScrollView>
);
};

Users must have a registered email/password account before they can log in. After a user logs in, all components wrapped in UserProvider have access to an instance of that user object through the useUser hook.

To log a user in with email and password:

  1. Register user if they aren't already.

  2. Destructure logIn and result from the useEmailPasswordAuth hook.

  3. Pass the user's email and password to LogIn() as an object.

  4. Handle the result.

export const LoginWithEmail = () => {
const {logIn, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const performLogin = () => {
logIn({email, password});
};
// Handle `result`...
};

Before you can register a new email/password user, you need to get their email address and password. The email address must not be associated with another email/password user and the password must be between 6 and 128 characters.

After registration, you must confirm a new user's email address before they can log in to your app.

To register a new user account:

  1. Destructure register and result from the useEmailPasswordAuth hook.

  2. Pass the user's email and password to register() as an object.

  3. Confirm the user's email address.

type RegisterButtonProps = {
email: string;
password: string;
};
const RegisterButton = ({email, password}: RegisterButtonProps) => {
const {register, result, logIn} = useEmailPasswordAuth();
// Log in the user after successful registration
useEffect(() => {
if (result.success && result.operation === AuthOperationName.Register) {
logIn({email, password});
}
}, [result, logIn, email, password]);
// For this example, the App Services backend automatically
// confirms users' emails.
const performRegistration = () => {
register({email, password});
};
return (
<Button
title="Register"
onPress={performRegistration}
/>
);
};

New users must confirm that they own their email address before they can log in to your app unless the provider is configured to automatically confirm new users. The confirmation process starts when you register a user and ends when you confirm them from your client code.

Email confirmation requries a valid token and tokenId. You get these values from different places depending on the provider configuration:

  • Send a confirmation email. The token and tokenId values are included as query parameters in the Email Confirmation URL.

  • Run a confirmation function. The token and tokenId values are passed to the function as arguments.

To confirm a registered user:

  1. In App Services, make sure User Confirmation Method is set to Send a confirmation email.

  2. In your client code, destructure confirm and result from the useEmailPasswordAuth hook.

  3. Pass token and tokenId to confirm() as an object.

  4. Handle confirmation based on result.

interface ConfirmUserProps {
token: string;
tokenId: string;
}
const ConfirmUser = ({token, tokenId}: ConfirmUserProps) => {
const {confirm, result} = useEmailPasswordAuth();
const performConfirmation = () => {
confirm({token, tokenId});
};
// Handle `result`...
}

The SDK provides methods to resend user confirmation emails or retry custom confirmation methods.

If the provider is configured to send a confirmation email, Atlas App Services automatically sends a confirmation email when a user registers. The email contains a link to the configured Email Confirmation URL with a token that is valid for 30 minutes. If a user does not follow the link and confirm within that period, they must request a new confirmation email.

To resend a confirmation email:

  1. Destructure resendConfirmationEmail and result from the useEmailPasswordAuth hook.

  2. Pass the user's email to resendConfirmationEmail() as an object.

  3. Handle confirmation based on result.

const ResendUserConfirmationEmail = () => {
const {resendConfirmationEmail, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const performResendConfirmationEmail = () => {
resendConfirmationEmail({email});
};
// Handle `result`...
}

You can rerun your custom confirmation function if needed.

To retry a user confirmation function:

  1. Destructure retryCustomConfirmation and result from the useEmailPasswordAuth hook.

  2. Pass the user's email to retryCustomConfirmation() as an object.

  3. Handle confirmation based on result.

const RetryCustomUserConfirmation = () => {
const {retryCustomConfirmation, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const performRetryCustomConfirmation = () => {
retryCustomConfirmation({email});
};
// Handle `result`...
}

Resetting a user's password is a multistep process.

  1. In your client app, provide a UI for a user to reset their password. Your App Services App can then send an email or run a custom function to confirm the user's identity.

  2. After confirming the user's identity, complete the password reset request.

  3. After the password reset finishes, the user can log in using the new password.

For more information about how to set your preferred password reset method, refer to the App Services Email/Password Authentication documentation.

You can send password reset emails to confirm users' identities. You must configure your App Services App to send a password reset email. Mobile applications can handle password resets directly in the app. Configure deep linking in Android or universal links in iOS.

The token and tokenId values from password reset emails are valid for 30 minutes. If users don't visit the email's Password Reset URL in that time, the values expire and users must request another password reset email.

To reset a password with email:

  1. In App Services, make sure Password Reset Method is set to Send a password reset email.

  2. In your client code, destructure sendResetPasswordEmail, resetPassword, and result from the useEmailPasswordAuth hook.

  3. Pass the user's email to sendResetPasswordEmail() as an object.

  4. Extract the token and tokenId values from the reset email password URL.

  5. Pass the new user password, token, and tokenId to resetPassword() as an object.

const SendResetPasswordEmailButton = ({email}: {email: string}) => {
const [errorMessage, setErrorMessage] = useState('');
const {sendResetPasswordEmail, result} = useEmailPasswordAuth();
const performSendResetPasswordEmail = () => {
sendResetPasswordEmail({email: email});
};
// Handle `result`...
};
interface ResetPasswordButtonProps {
password: string;
token: string;
tokenId: string;
}
const ResetPasswordButton = ({
password,
token,
tokenId,
}: ResetPasswordButtonProps) => {
const [errorMessage, setErrorMessage] = useState('');
const {resetPassword, result} = useEmailPasswordAuth();
const performPasswordReset = () => {
resetPassword({token, tokenId, password});
};
// Handle `result`...
};

You can call an App Services Function that you define to handle password resets. You must configure your App Services App to run a password reset function.

This function can take a username, a password, and any number of additional arguments. You can use these arguments to specify details like security question answers or other challenges that the user should pass to successfully complete a password reset.

On the App Services side, you define the custom password reset function that runs when you call this method. That function should return one of three possible statuses:

  • fail

  • pending

  • success

A fail status is treated as an error. The SDK method callResetPasswordFunction() does not take return values, so it does not return a pending or success status to the client.

To call a password reset function:

  1. In App Services, create a password reset function.

  2. In App Services, make sure Password Reset Method is set to Run a password reset function and point it to your new function.

  3. In your client code, destructure callResetPasswordFunction and result from the useEmailPasswordAuth hook.

  4. Pass the user's email and password to callResetPasswordFunction() as an object, followed by any other arguments you defined for your custom function.

const ResetPasswordWithFunction = () => {
const {callResetPasswordFunction, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const performResetPassword = () => {
callResetPasswordFunction({email, password}, "extraArg1", "extraArg2");
};
}

Your App Services password reset function may return pending if you want the user to take some additional step to confirm their identity. However, that return value is not passed to the SDK's callResetPasswordFunction(), so your client app must implement its own logic to handle a pending status.

Your server-side function might send an email using a custom email provider. Or you may use SMS to confirm the user's identity via text message.

You have access to a token and tokenId in the App Services password reset function context. If you pass this information from your App Services password reset function, you can pass these values back to your app using platform-specific deep linking or universal links. Then, your client application can use the useEmailPasswordAuth hook to complete the password reset flow.

interface ResetPasswordButtonProps {
password: string;
token: string;
tokenId: string;
}
const ResetPasswordButton = ({
password,
token,
tokenId,
}: ResetPasswordButtonProps) => {
const [errorMessage, setErrorMessage] = useState('');
const {resetPassword, result} = useEmailPasswordAuth();
const performPasswordReset = () => {
resetPassword({token, tokenId, password});
};
// Handle `result`...
};

If your App Services password reset function does additional validation within the function, or if you have validated the user's identity prior to attempting to reset the password, you may configure the App Services function to return success. However, that return value is not passed to the SDK's callResetPasswordFunction(), so your client app must implement its own logic to handle a success status.

The useEmailPasswordAuth hook has methods to streamline managing email/password users. It also has state related to authentication. Refer to the useEmailPasswordAuth reference for details.

You can also check out the @realm/react API documentation for useEmailPasswordAuth.

←  Custom User Data - React Native SDKMulti-User Applications - React Native SDK →