Email Verification Logic - abhiram-shaji/Langroove GitHub Wiki

Developer Documentation: useEmailVerification.ts Hook

This documentation explains the implementation of the email verification feature using the useEmailVerification hook. The hook simplifies managing email verification states and handling user navigation after successful verification.


Overview

The useEmailVerification hook:

  1. Monitors the authentication state of the current user.
  2. Redirects verified users to the main application (TabScreens).
  3. Provides utility functions for checking verification status and resending verification emails.

Features and Caching

1. User State Caching

Purpose

  • To ensure the app remembers the current user's state without unnecessary re-authentication requests.

Implementation

  1. Real-time User State Monitoring:

    • Uses Firebase's onAuthStateChanged to track authentication state changes.
    • If the user's email is verified, they are redirected to the main feed.
  2. Code Snippet:

    useEffect(() => {
      const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
        setUser(currentUser);
        if (currentUser?.emailVerified) {
          navigation.replace('TabScreens', { screen: 'Feed' }); // Navigate to Feed
        } else {
          setLoading(false);
        }
      });
      return unsubscribe; // Clean up listener on unmount
    }, [navigation]);
    
  3. Process:

    • Firebase caches the authentication state locally.
    • The hook reads from this cache to quickly determine the user's state, minimizing redundant calls to the authentication service.

2. Verification Status Check

Purpose

  • To reload and fetch the most up-to-date user information, ensuring the verification status reflects changes made outside the app.

Implementation

  1. Functionality:

    • The reload method updates the cached user object with the latest server data.
  2. Code Snippet:

    const checkVerificationStatus = async () => {
      if (user) {
        setLoading(true);
        try {
          await reload(user);
          const updatedUser = auth.currentUser;
          setUser(updatedUser);
          if (updatedUser?.emailVerified) {
            navigation.replace('TabScreens', { screen: 'Feed' });
          }
        } catch (error) {
          console.error('Error reloading user:', error);
          Alert.alert('Error', 'Could not refresh verification status. Please try again later.');
        } finally {
          setLoading(false);
        }
      }
    };
    
  3. Process:

    • Calls reload(user) to fetch the latest data.
    • Checks the updated emailVerified flag to determine whether to navigate the user to the main feed.

3. Resend Verification Email

Purpose

  • To provide a user-friendly way for resending the verification email if the user has not verified their email address yet.

Implementation

  1. Functionality:

    • Calls Firebase's sendEmailVerification method to trigger the email.
  2. Code Snippet:

    const handleResendVerification = () => {
      if (user) {
        sendEmailVerification(user)
          .then(() => {
            Alert.alert(
              'Verification Email Sent',
              'A new verification email has been sent to your email address.'
            );
          })
          .catch((error) => {
            console.error('Error sending verification email:', error);
            Alert.alert('Error', 'Failed to send verification email. Please try again later.');
          });
      }
    };
    
  3. Process:

    • Ensures the user is logged in before attempting to resend the email.
    • Provides success or error feedback via an alert.

Key Properties and Methods

Property/Method Description
loading Indicates whether the hook is performing a background operation.
user The currently authenticated user (or null if no user is logged in).
checkVerificationStatus Reloads the user and updates their verification status.
handleResendVerification Sends a new verification email to the user's email address.

Notes

  • Caching Benefits:

    • Authentication state changes are cached locally, improving responsiveness and reducing server calls.
    • The reload method ensures cached data is always up-to-date when needed.
  • Error Handling:

    • Alerts inform users of issues like failed email verification requests or refresh operations.

For further configuration or troubleshooting, refer to the Firebase Authentication Documentation.