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
1
Check if user is authenticated
If
isAuthenticated is false, the user is redirected to /login2
Allow authenticated users
If authenticated, proceed to the next validation level
Level 2: Role-Based Access
1
Check if role is required
If
requeridRole is specified, validate the user’s role2
Validate role match
If the user’s
role doesn’t match requeridRole, redirect to home page3
Grant access
If role matches (or no role required), render the protected content
Props
boolean
required
Whether the user is currently authenticated
React.ReactNode
required
The protected component/content to render if access is granted
string
The current user’s role (e.g., “admin” or “cliente”)
string
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:
1
User logs in
AuthContext validates credentials and sets:isAuthenticatedtotrueroleto user’s role from users.json- Stores both in localStorage
2
Route protection activated
When user navigates to a protected route,
RutaProtegida checks:- Authentication status from
AuthContext - User role from
AuthContext
3
Access decision
Based on validation results:
- Grant access and render protected content
- Redirect to login if not authenticated
- Redirect to home if wrong role
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