7.7 KiB
Route Protection and Access Control Implementation
This document describes the comprehensive route protection and access control system implemented for the car maintenance management system.
Overview
The route protection system provides:
- Authentication middleware for all protected routes
- Role-based access control (RBAC) with three levels: Superadmin, Admin, User
- Automatic redirection for unauthorized access attempts
- Session validation and user status checking
- Route-specific protection functions
- Permission checking utilities
- Redirect authenticated users from auth pages (signin/signup)
Authentication Levels
The system uses a hierarchical authentication system where lower numbers indicate higher privileges:
| Level | Name | Value | Description |
|---|---|---|---|
| 1 | Superadmin | 1 | Full system access, can manage admins |
| 2 | Admin | 2 | Can manage users and business data |
| 3 | User | 3 | Basic access to operational features |
Route Protection Matrix
| Route | Auth Required | Min Level | Superadmin | Admin | User |
|---|---|---|---|---|---|
/dashboard |
✓ | User (3) | ✓ | ✓ | ✓ |
/users |
✓ | Admin (2) | ✓ | ✓ | ✗ |
/customers |
✓ | User (3) | ✓ | ✓ | ✓ |
/vehicles |
✓ | User (3) | ✓ | ✓ | ✓ |
/maintenance-visits |
✓ | User (3) | ✓ | ✓ | ✓ |
/financial |
✓ | Admin (2) | ✓ | ✓ | ✗ |
/admin/enable-signup |
✓ | Super (1) | ✓ | ✗ | ✗ |
/signin |
✗ | None | ✓* | ✓* | ✓* |
/signup |
✗ | None | ✓* | ✓* | ✓* |
* Authenticated users are redirected away from auth pages
Implementation Details
Core Middleware Functions
requireAuthentication(request, options?)
- Ensures user is logged in and active
- Options:
allowInactive,redirectTo - Redirects to
/signinif not authenticated - Checks user status (active/inactive)
requireAdmin(request, options?)
- Requires Admin level (2) or higher
- Calls
requireAuthLevelwithAUTH_LEVELS.ADMIN
requireSuperAdmin(request, options?)
- Requires Superadmin level (1)
- Calls
requireAuthLevelwithAUTH_LEVELS.SUPERADMIN
redirectIfAuthenticated(request, redirectTo?)
- Redirects authenticated users away from auth pages
- Default redirect:
/dashboard - Only redirects active users
Route-Specific Protection Functions
protectUserManagementRoute(request)
- Used by
/usersroute - Requires Admin level or higher
- Additional business logic validation
protectFinancialRoute(request)
- Used by
/financialroute - Requires Admin level or higher
protectCustomerRoute(request)
- Used by
/customersroute - Requires any authenticated user
protectVehicleRoute(request)
- Used by
/vehiclesroute - Requires any authenticated user
protectMaintenanceRoute(request)
- Used by
/maintenance-visitsroute - Requires any authenticated user
Permission Checking
checkPermission(user, permission)
Checks specific permissions for a user:
| Permission | Superadmin | Admin | User |
|---|---|---|---|
view_all_users |
✓ | ✗ | ✗ |
create_users |
✓ | ✓ | ✗ |
manage_finances |
✓ | ✓ | ✗ |
view_reports |
✓ | ✓ | ✗ |
Session Validation
validateSession(request)
Returns session validation result:
{
isValid: boolean;
user: SafeUser | null;
error?: 'no_user' | 'inactive_user' | 'session_error';
}
Error Handling
createUnauthorizedResponse(message?)
- Creates 403 Forbidden response
- Default message in Arabic
- Custom message support
Usage Examples
Protecting a Route
// In route loader
export async function loader({ request }: LoaderFunctionArgs) {
const user = await requireAdmin(request);
return json({ user });
}
Custom Protection
// In route loader with custom options
export async function loader({ request }: LoaderFunctionArgs) {
const user = await requireAuthentication(request, {
redirectTo: "/custom-login",
allowInactive: false
});
return json({ user });
}
Permission Checking
// In component or route
const canManageUsers = checkPermission(user, 'create_users');
if (canManageUsers) {
// Show user management UI
}
Conditional Access Control
// Signup route with conditional access
export async function loader({ request }: LoaderFunctionArgs) {
await redirectIfAuthenticated(request);
const signupAllowed = await isSignupAllowed();
if (!signupAllowed && !adminOverride) {
return redirect("/signin?error=signup_disabled");
}
return json({ signupAllowed });
}
Security Features
Authentication Security
- ✓ Secure session management with httpOnly cookies
- ✓ Password hashing with bcrypt
- ✓ Session expiration handling
- ✓ CSRF protection through Remix forms
Authorization Security
- ✓ Role-based access control (RBAC)
- ✓ Route-level protection
- ✓ API endpoint authorization
- ✓ User status validation (active/inactive)
Error Handling
- ✓ Graceful error responses
- ✓ Proper HTTP status codes
- ✓ Localized error messages (Arabic)
- ✓ Secure error information disclosure
Testing
The route protection system includes comprehensive tests:
Integration Tests
- Permission checking logic
- Auth level hierarchy validation
- Error response creation
- User status validation
Route Tests
- Authentication requirement verification
- Role-based access control
- Redirection behavior
- Error handling
Requirements Compliance
This implementation satisfies the following requirements:
Requirement 6.1: User Authentication Levels
✓ Supports three auth levels: 1=superadmin, 2=admin, 3=user
Requirement 6.2: Admin User Visibility
✓ Admins cannot see superadmin accounts ✓ Superadmins can see all user accounts
Requirement 6.3: User Status Management
✓ Supports "active" and "inactive" status ✓ Inactive users are properly handled
Requirement 6.4: Conditional Signup Access
✓ Signup restricted when admin users exist ✓ Signup allowed when no admin users exist
Future Enhancements
Potential improvements for the route protection system:
- Rate Limiting: Add rate limiting for authentication attempts
- Audit Logging: Log access attempts and authorization failures
- Session Management: Advanced session management with refresh tokens
- Multi-Factor Authentication: Add MFA support for admin accounts
- API Key Authentication: Support for API access with keys
- Permission Caching: Cache permission checks for performance
- Dynamic Permissions: Database-driven permission system
Troubleshooting
Common Issues
- Redirect Loops: Check for circular redirects in auth logic
- Session Expiry: Ensure proper session renewal
- Permission Denied: Verify user auth level and status
- Inactive Users: Check user status in database
Debug Information
Enable debug logging by setting environment variables:
DEBUG=auth:*
LOG_LEVEL=debug
This will provide detailed information about authentication and authorization decisions.