Login Logic - abhiram-shaji/Langroove GitHub Wiki

Developer Documentation: useLogin Hook

This documentation outlines the implementation and functionality of the useLogin hook, which handles user login, validation, and navigation in a Firebase-authenticated React Native application.


Overview

The useLogin hook provides:

  1. State management for user credentials and error handling.
  2. Login functionality using Firebase Authentication.
  3. Navigation to related screens like SignUp and ForgotPassword.
  4. Email verification handling for unverified accounts.

Features and Functionality

1. State Management

Purpose

  • Manages user input (email, password) and tracks the loading state and error messages.

Implementation

  1. State Variables:

    • credentials: Stores the user's email and password.
    • loading: Tracks the loading state during the login process.
    • error: Stores error messages for validation and authentication failures.
  2. Code Snippet:

    const [credentials, setCredentials] = useState<Credentials>({ email: '', password: '' });
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    
  3. Input Handling:

    • handleInputChange updates the credentials state and clears errors when the user types.
    const handleInputChange = (field: keyof Credentials, value: string) => {
      setCredentials((prev) => ({ ...prev, [field]: value }));
      setError(''); // Clear error when user types
    };
    

2. Field Validation

Purpose

  • Ensures that both the email and password fields are filled before proceeding with login.

Implementation

  1. Functionality:

    • Validates that email and password are non-empty.
    • Displays an error message if validation fails.
  2. Code Snippet:

    const validateFields = (): boolean => {
      if (!credentials.email || !credentials.password) {
        setError('Email and password should not be empty');
        return false;
      }
      return true;
    };
    

3. Login with Firebase

Purpose

  • Authenticates the user using Firebase's signInWithEmailAndPassword method.
  • Handles scenarios for unverified email accounts and redirects appropriately.

Implementation

  1. Functionality:

    • Attempts to sign in the user.
    • If the email is unverified:
      • Sends a verification email.
      • Redirects to the WaitingForVerification screen.
    • Navigates to the Feed screen upon successful login and verification.
  2. Code Snippet:

    const handleLogin = async () => {
      if (!validateFields()) return;
    
      setLoading(true);
    
      try {
        const userCredential = await signInWithEmailAndPassword(auth, credentials.email, credentials.password);
        const user = userCredential.user;
    
        if (!user.emailVerified) {
          await sendEmailVerification(user);
          setError('Email not verified. Please check your email and verify your account.');
          navigation.reset({
            index: 0,
            routes: [{ name: 'WaitingForVerification' }],
          });
          return;
        }
    
        navigation.navigate('TabScreens', { screen: 'Feed' });
      } catch (error: any) {
        const errorMessage = getErrorMessage(error.code);
        setError(errorMessage);
      } finally {
        setLoading(false);
      }
    };
    
  3. Process:

    • Validates fields before proceeding.
    • Handles authentication errors using a custom error mapping (useFirebaseAuthErrors).
    • Manages unverified email cases by sending a verification email and redirecting to the appropriate screen.

4. Navigation

Purpose

  • Provides navigation to related screens like SignUp and ForgotPassword.

Implementation

  1. Functionality:

    • Navigates to SignUp or ForgotPassword using React Navigation's navigate method.
  2. Code Snippets:

    const navigateToSignUp = () => {
      navigation.navigate('SignUp');
    };
    
    const navigateToForgotPassword = () => {
      navigation.navigate('ForgotPassword');
    };
    

Key Properties and Methods

Property/Method Description
credentials Stores user email and password.
loading Indicates whether the login process is ongoing.
error Stores a single error message for UI feedback.
handleInputChange(field, value) Updates the specified credential field and clears errors.
handleLogin() Authenticates the user, manages unverified emails, and handles navigation.
navigateToSignUp() Redirects to the SignUp screen.
navigateToForgotPassword() Redirects to the ForgotPassword screen.

Error Handling

  • Validation Errors:
    • Displays "Email and password should not be empty" if fields are left blank.
  • Authentication Errors:
    • Uses useFirebaseAuthErrors to map Firebase error codes to user-friendly messages.
  • Unverified Email:
    • Sends a verification email and redirects to the WaitingForVerification screen with an error message.

Notes

  • Firebase automatically handles user sessions after successful login.
  • The reset method is used instead of replace to clear the navigation stack when redirecting to WaitingForVerification.

For further configuration or troubleshooting, consult the Firebase Authentication Documentation.