Frontend Authentication State
Relevant source files
The following files were used as context for generating this wiki page:
The Frontend Authentication State is a centralized management system built using the React Context API to handle user identity, session persistence, and access control across the application. It serves as the single source of truth for the current user's status, enabling conditional rendering of UI elements and enforcing security through route protection.
The system integrates local storage for session persistence, service layers for API interaction, and dedicated UI components for login and registration. It ensures that authenticated data, such as user profiles and authorization tokens, are available to all child components within the application's component tree.
Sources: Front/src/context/AuthContext.jsx, Front/src/App.js:12-22
Authentication Architecture
The architecture relies on an AuthProvider component that wraps the application. It manages a user state which is initialized by checking localStorage for existing session data.
Core Components and Logic
- AuthContext: Created using
createContext(null), it provides theuserobject and action functions (login,logout,register) to the application. - AuthProvider: A provider component that utilizes the
useStateanduseEffecthooks to synchronize the authentication state with the browser's local storage. - useAuth: A custom hook that simplifies access to the authentication context for functional components.
Sources: Front/src/context/AuthContext.jsx:3-10, Front/src/context/AuthContext.jsx:38-42
State Persistence Flow
The following diagram illustrates how the authentication state is synchronized with persistent storage to maintain sessions across page reloads.
Authentication Actions
The system defines three primary operations to manage the lifecycle of a user session.
| Action | Description | Data Persistence |
|---|---|---|
| Login | Updates the state with user data retrieved from a successful credential match. | Sets user in localStorage. |
| Logout | Resets the user state to null and clears session-related data. | Removes user and chats from localStorage. |
| Register | Creates a new user object with a unique ID and persists it to a mock database. | Updates registeredUsers in localStorage. |
Sources: Front/src/context/AuthContext.jsx:23-37
Login Implementation Details
The login process involves validating user input against a collection of registered users stored in localStorage. Upon success, the login function is invoked to update the global state and navigate the user to the home page.
Sources: Front/src/pages/login.jsx:30-46
API Integration (Service Layer)
While the context handles state, the authService in the service layer manages the actual network requests to the backend for token-based authentication.
export const authService = {
login: async (credenciales) => {
const response = await fetch(`${API_BASE_URL}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credenciales)
});
return handleResponse(response);
},
logout: () => {
localStorage.removeItem('token');
}
};
Sources: Front/src/services/api.js:125-141
Access Control and Route Protection
Authentication state is used to restrict access to specific views. This is achieved through the ProtectedRoute component and conditional rendering in the navigation bar.
ProtectedRoute Component
The ProtectedRoute acts as a wrapper for routes that require an active session. If the user state is null, it redirects the visitor to the login page.
Sources: Front/src/components/ProtectedRoute.jsx:4-13
Conditional UI Rendering
The AppNavbar uses the user object to toggle the visibility of specific navigation links (e.g., "Publicar", "Mis productos") and the authentication buttons ("Cerrar sesión" vs "Iniciar sesión").
Sources: Front/src/components/navbar.jsx:18-53
Data Models
The system interacts with user data structured for both local state and API communication.
User Schema
| Field | Type | Description |
|---|---|---|
id / slug | String/Number | Unique identifier for the user. |
name | String | Full name or display name. |
email | String | User's primary email address (used for login). |
password | String | Account password (stored in plain text in mock DB). |
token | String | JWT or session token retrieved from headers. |
Sources: Front/src/context/AuthContext.jsx:31-34, Front/src/services/api.js:10-14, Front/src/pages/register.jsx:11-16
Summary
The Frontend Authentication State provides a robust framework for managing user sessions within the application. By leveraging the React Context API and localStorage, the system ensures that user data is persistent, routes are secure, and the user interface remains responsive to the authentication status. It bridges the gap between raw API responses and the component-level logic required for a modern web experience.