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.
Prerequisites
Before you can authenticate a user, you must:
Enable email/password authentication in the App. For details, refer to Email/Password Authentication in the App Services documentation.
Configure User Authentication in Client
@realm/react
has providers and hooks for user authentication. To configure
user authentication:
Set up
@realm/react
providers.Log a user in with a
UserProvider
fallback component.
Set up @realm/react Providers
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:
Wrap all components that need to access App Services in
AppProvider
.Inside of
AppProvider
, wrap all components that you want to have access to an authenticated user withUserProvider
.In
UserProvider
, include afallback
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> ); };
Log In with a Fallback Component
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:
Register user if they aren't already.
Destructure
logIn
andresult
from theuseEmailPasswordAuth
hook.Pass the user's email and password to
LogIn()
as an object.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`... };
Register a New User Account
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:
Destructure
register
andresult
from theuseEmailPasswordAuth
hook.Pass the user's email and password to
register()
as an object.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} /> ); };
Confirm a User's Email Address
New users must confirm that they own their email address before they can log in to your app unless the auth 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 auth provider configuration:
Send a confirmation email. The
token
andtokenId
values are included as query parameters in the Email Confirmation URL.Run a confirmation function. The
token
andtokenId
values are passed to the function as arguments.
To confirm a registered user:
In App Services, make sure User Confirmation Method is set to Send a confirmation email.
In your client code, destructure
confirm
andresult
from theuseEmailPasswordAuth
hook.Pass
token
andtokenId
toconfirm()
as an object.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`... }
Retry User Confirmation Methods
The SDK provides methods to resend user confirmation emails or retry custom confirmation methods.
Resend a Confirmation Email
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:
Destructure
resendConfirmationEmail
andresult
from theuseEmailPasswordAuth
hook.Pass the user's email to
resendConfirmationEmail()
as an object.Handle confirmation based on
result
.
const ResendUserConfirmationEmail = () => { const {resendConfirmationEmail, result} = useEmailPasswordAuth(); const [email, setEmail] = useState(''); const performResendConfirmationEmail = () => { resendConfirmationEmail({email}); }; // Handle `result`... }
Retry a User Confirmation Function
You can rerun your custom confirmation function if needed.
To retry a user confirmation function:
Destructure
retryCustomConfirmation
andresult
from theuseEmailPasswordAuth
hook.Pass the user's email to
retryCustomConfirmation()
as an object.Handle confirmation based on
result
.
const RetryCustomUserConfirmation = () => { const {retryCustomConfirmation, result} = useEmailPasswordAuth(); const [email, setEmail] = useState(''); const performRetryCustomConfirmation = () => { retryCustomConfirmation({email}); }; // Handle `result`... }
Reset a User's Password
Resetting a user's password is a multistep process.
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.
After confirming the user's identity, complete the password reset request.
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.
Reset Password with Email
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:
In App Services, make sure Password Reset Method is set to Send a password reset email.
In your client code, destructure
sendResetPasswordEmail
,resetPassword
, andresult
from theuseEmailPasswordAuth
hook.Pass the user's email to
sendResetPasswordEmail()
as an object.Extract the
token
andtokenId
values from the reset email password URL.Pass the new user password,
token
, andtokenId
toresetPassword()
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`... };
Call a Password Reset Function
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:
In App Services, create a password reset function.
In App Services, make sure Password Reset Method is set to Run a password reset function and point it to your new function.
In your client code, destructure
callResetPasswordFunction
andresult
from theuseEmailPasswordAuth
hook.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"); }; }
Server-Side Pending Case
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`... };
Server-Side Success Case
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.
useEmailPasswordAuth Hook Reference
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.