Overview
TheAuthContext manages user authentication, login state, and role-based access control. It handles login/logout operations and persists authentication state to localStorage.
Source: ~/workspace/source/src/context/AuthContext.jsx
Setup
Wrap your application with theAuthProvider (must be inside Router):
Usage
Use theuseAuth custom hook to access authentication context:
State Properties
isAuthenticated
boolean
Whether a user is currently logged in. Synced with localStorage on mount.
role
string
Current user’s role. Either
'admin' or 'cliente'. Empty string when not authenticated.string
Email input value for the login form.
setEmail
function
Update the email input value.
password
string
Password input value for the login form.
setPassword
function
Update the password input value.
errors
object
Validation and authentication error messages. Keys:
email, password.setErrors
function
Update error messages. Useful for clearing errors.
setIsAuth
function
Manually set authentication state. Used for logout.
Methods
handleSubmit
Processes login form submission, validates credentials, and redirects based on user role.Event
required
Form submit event. Will be prevented from default behavior.
- Validates email and password are not empty
- Fetches user data from
data/users.json - Matches credentials against user database
- Sets authentication state and role
- Saves to localStorage:
isAuthandrole - Redirects:
- Admin users →
/admin - Regular users →
/
- Admin users →
- Empty email:
"Email es requerido" - Empty password:
"Password es requerido" - Invalid credentials:
"credenciales invalidas" - Server error:
"Algo salió mal. Por favor, inténtalo de nuevo más tarde."
src/layout/Login.jsx
Authentication Flow
Login Process
- User enters email and password
- Form submission calls
handleSubmit(e) - Client-side validation checks for empty fields
- Fetches user database from
data/users.json - Searches for matching email and password
- On success:
- Sets
isAuthenticated = true - Sets
rolebased on user data - Saves to localStorage
- Navigates to appropriate route
- Sets
- On failure:
- Sets error message
- User remains on login page
Auto-Login on Mount
The context checks localStorage on mount:Logout Implementation
To implement logout, clear localStorage and reset auth state:Protected Routes
Use authentication state to protect routes:src/App.jsx
User Data Structure
The authentication system expects adata/users.json file with this structure:
Security Notes
Complete Implementation Example
src/App.jsx