Skip to main content

useAuth Hook

The useAuth hook provides complete authentication functionality including login, registration, logout, and onboarding management. It integrates with Redux for global state management.

Import

import { useAuth } from '@hooks/useAuth';

Basic Usage

import { useAuth } from '@hooks/useAuth';

function LoginPage() {
  const { 
    email, 
    setEmail, 
    password, 
    setPassword, 
    handleLogin, 
    isLoading, 
    error 
  } = useAuth();
  
  return (
    <form onSubmit={handleLogin}>
      <input value={email} onChange={(e) => setEmail(e.target.value)} />
      <input 
        type="password" 
        value={password} 
        onChange={(e) => setPassword(e.target.value)} 
      />
      <button type="submit" disabled={isLoading}>
        {isLoading ? 'Logging in...' : 'Login'}
      </button>
      {error && <p>{error}</p>}
    </form>
  );
}

Return Value

The hook returns an object containing all auth state and functions:

Authentication State (from Redux)

user
User | null
The currently authenticated user object, or null if not logged in.
interface User {
  id: string;
  branchIds: string[];
  nombre: string;
  email: string;
  rol: UserRole;
}
token
string | null
JWT authentication token for API requests.
isAuthenticated
boolean
true if user is logged in, false otherwise.
isLoading
boolean
true during login/register operations.
error
string | null
Error message from failed authentication attempts, or null if no error.
needsOnboarding
boolean
true if user is newly registered and needs to complete onboarding.

Form State

email
string
Current email input value (default: ‘[email protected]’ for demo).
setEmail
(email: string) => void
Function to update email state.
password
string
Current password input value (default: ‘123456’ for demo).
setPassword
(password: string) => void
Function to update password state.

Authentication Functions

handleLogin
(e?: React.FormEvent) => Promise<boolean>
Attempts to log in with current email and password.Parameters:
  • e (optional) - Form event to prevent default submission
Returns: Promise that resolves to true if login successful, false otherwise.Behavior:
  • Sets loading state
  • Validates credentials against mock user database
  • Dispatches Redux actions for success/failure
  • Simulates network latency (1.5s)
register
(nombreNuevo: string, emailNuevo: string, passwordNuevo?: string) => Promise<boolean>
Registers a new user as system owner.Parameters:
  • nombreNuevo - Full name of new user
  • emailNuevo - Email address for new account
  • passwordNuevo (optional) - Password for new account
Returns: Promise that resolves to true if registration successful, false otherwise.Behavior:
  • Checks if email already exists
  • Creates new user with OWNER role
  • Sets isNew: true to trigger onboarding
  • Automatically logs in the new user
logout
() => void
Logs out the current user and clears authentication state.
finishOnboarding
() => void
Marks the onboarding process as complete for new users.

Examples

Complete Login Flow

import { useAuth } from '@hooks/useAuth';
import { Button } from '@components/ui/Button';
import { Input } from '@components/ui/Input';

function LoginPage() {
  const { 
    email, 
    setEmail, 
    password, 
    setPassword, 
    handleLogin, 
    isLoading, 
    error 
  } = useAuth();
  
  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const success = await handleLogin();
    if (success) {
      // Redirect to dashboard
      navigate('/dashboard');
    }
  };
  
  return (
    <form onSubmit={onSubmit}>
      <div>
        <label>Email</label>
        <Input 
          type="email"
          value={email} 
          onChange={(e) => setEmail(e.target.value)}
          placeholder="[email protected]"
        />
      </div>
      
      <div>
        <label>Password</label>
        <Input 
          type="password"
          value={password} 
          onChange={(e) => setPassword(e.target.value)}
        />
      </div>
      
      {error && (
        <div className="error-message">
          {error}
        </div>
      )}
      
      <Button 
        type="submit" 
        variant="primary" 
        fullWidth
        isLoading={isLoading}
      >
        Login
      </Button>
    </form>
  );
}

Registration Flow

import { useState } from 'react';
import { useAuth } from '@hooks/useAuth';

function RegisterPage() {
  const { register, isLoading, error } = useAuth();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  
  const handleRegister = async () => {
    const success = await register(name, email);
    if (success) {
      // User is automatically logged in and onboarding starts
      navigate('/onboarding');
    }
  };
  
  return (
    <div>
      <h2>Create Your Account</h2>
      <Input 
        placeholder="Full Name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <Input 
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <Button 
        onClick={handleRegister} 
        isLoading={isLoading}
      >
        Create Account
      </Button>
      {error && <p>{error}</p>}
    </div>
  );
}

Protected Route with Auth Check

import { Navigate } from 'react-router-dom';
import { useAuth } from '@hooks/useAuth';

function ProtectedRoute({ children }) {
  const { isAuthenticated, isLoading } = useAuth();
  
  if (isLoading) {
    return <div>Loading...</div>;
  }
  
  if (!isAuthenticated) {
    return <Navigate to="/login" />;
  }
  
  return children;
}

User Profile Display

import { useAuth } from '@hooks/useAuth';

function UserProfile() {
  const { user, logout } = useAuth();
  
  if (!user) return null;
  
  return (
    <div>
      <h2>Welcome, {user.nombre}</h2>
      <p>Email: {user.email}</p>
      <p>Role: {user.rol}</p>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

Onboarding Flow

import { useAuth } from '@hooks/useAuth';
import { useEffect } from 'react';

function OnboardingWizard() {
  const { needsOnboarding, finishOnboarding } = useAuth();
  
  useEffect(() => {
    if (!needsOnboarding) {
      // Redirect to dashboard if onboarding already complete
      navigate('/dashboard');
    }
  }, [needsOnboarding]);
  
  const completeOnboarding = () => {
    // Save onboarding data
    // ...
    
    // Mark onboarding as complete
    finishOnboarding();
    navigate('/dashboard');
  };
  
  return (
    <div>
      <h2>Welcome to MotorDesk</h2>
      {/* Onboarding steps */}
      <Button onClick={completeOnboarding}>
        Complete Setup
      </Button>
    </div>
  );
}

User Roles

enum UserRole {
  OWNER = 'OWNER',           // Full system access
  ADMIN = 'ADMIN',           // Administrative access
  SUPERVISOR = 'SUPERVISOR', // Supervisory access
  SELLER = 'SELLER'          // Basic sales access
}

Mock Users (Development)

The hook uses a mock user database for development:
// Example mock users
{
  email: '[email protected]',
  password: '123456', // All mock users use this password
  nombre: 'Carlos Rodríguez',
  rol: UserRole.OWNER
}

Redux Integration

The hook dispatches these Redux actions:
  • loginStart() - Sets loading state
  • loginSuccess({ user, token, isNew }) - Stores authenticated user
  • loginFailure(errorMessage) - Stores error message
  • logout() - Clears auth state
  • completeOnboarding() - Marks onboarding complete

Error Messages

Possible error messages:
  • “Credenciales incorrectas. Verifica tu correo o contraseña.” - Invalid credentials
  • “Ocurrió un error interno al intentar iniciar sesión.” - Server error during login
  • “Este correo ya está registrado en el sistema.” - Email already exists during registration
  • “Error en el registro del sistema.” - Server error during registration

State Management Flow

The hook includes default credentials ([email protected] / 123456) for quick prototyping. Remove these in production.
This is a mock implementation. In production, replace the mock user database with actual API calls to your authentication backend.

Source Code

Location: /home/daytona/workspace/source/src/hooks/useAuth.ts:1

Build docs developers (and LLMs) love