RutaProtegida component to restrict access to certain routes based on authentication status and user roles.
RutaProtegida Component
The route protection component is located at/workspace/source/src/auth/RutaProtegida.jsx and implements a simple but effective access control system.
Component Structure
/workspace/source/src/auth/RutaProtegida.jsx:4-12
How It Works
The component performs two levels of validation:Level 1: Authentication Check
Level 2: Role-Based Access
Props
Whether the user is currently authenticated
The protected component/content to render if access is granted
The current user’s role (e.g., “admin” or “cliente”)
The role required to access this route (e.g., “admin”)
Usage Example
Protecting the admin route:- User must be logged in
- User must have the “admin” role
- Otherwise, redirect appropriately
Access Flow Diagram
Integration with Auth System
TheRutaProtegida component works in conjunction with AuthContext:
User logs in
AuthContext validates credentials and sets:isAuthenticatedtotrueroleto user’s role from users.json- Stores both in localStorage
Route protection activated
When user navigates to a protected route,
RutaProtegida checks:- Authentication status from
AuthContext - User role from
AuthContext
Common Scenarios
Anonymous user tries to access admin panel
Anonymous user tries to access admin panel
Result: Redirected to
/loginReason: isAuthenticated is falseClient user tries to access admin panel
Client user tries to access admin panel
Result: Redirected to
/ (home page)Reason: role is “cliente” but requeridRole is “admin”Admin user accesses admin panel
Admin user accesses admin panel
Result: Access grantedReason:
isAuthenticated is true and role matches requeridRoleAuthenticated user accesses unprotected route
Authenticated user accesses unprotected route
Result: Access grantedReason: No
requeridRole specified, only authentication requiredSecurity Considerations
What it protects
- UI routes and components
- User experience flow
- Prevents accidental access
What it doesn't protect
- API endpoints (needs backend auth)
- Direct data access
- Malicious users with dev tools
For production applications, always implement:
- Server-side authentication
- API endpoint protection
- Token-based authentication (JWT)
- Secure password hashing