250 lines
7.7 KiB
Markdown
250 lines
7.7 KiB
Markdown
# 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 `/signin` if not authenticated
|
|
- Checks user status (active/inactive)
|
|
|
|
#### `requireAdmin(request, options?)`
|
|
- Requires Admin level (2) or higher
|
|
- Calls `requireAuthLevel` with `AUTH_LEVELS.ADMIN`
|
|
|
|
#### `requireSuperAdmin(request, options?)`
|
|
- Requires Superadmin level (1)
|
|
- Calls `requireAuthLevel` with `AUTH_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 `/users` route
|
|
- Requires Admin level or higher
|
|
- Additional business logic validation
|
|
|
|
#### `protectFinancialRoute(request)`
|
|
- Used by `/financial` route
|
|
- Requires Admin level or higher
|
|
|
|
#### `protectCustomerRoute(request)`
|
|
- Used by `/customers` route
|
|
- Requires any authenticated user
|
|
|
|
#### `protectVehicleRoute(request)`
|
|
- Used by `/vehicles` route
|
|
- Requires any authenticated user
|
|
|
|
#### `protectMaintenanceRoute(request)`
|
|
- Used by `/maintenance-visits` route
|
|
- 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:
|
|
```typescript
|
|
{
|
|
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
|
|
```typescript
|
|
// In route loader
|
|
export async function loader({ request }: LoaderFunctionArgs) {
|
|
const user = await requireAdmin(request);
|
|
return json({ user });
|
|
}
|
|
```
|
|
|
|
### Custom Protection
|
|
```typescript
|
|
// 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
|
|
```typescript
|
|
// In component or route
|
|
const canManageUsers = checkPermission(user, 'create_users');
|
|
if (canManageUsers) {
|
|
// Show user management UI
|
|
}
|
|
```
|
|
|
|
### Conditional Access Control
|
|
```typescript
|
|
// 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:
|
|
|
|
1. **Rate Limiting**: Add rate limiting for authentication attempts
|
|
2. **Audit Logging**: Log access attempts and authorization failures
|
|
3. **Session Management**: Advanced session management with refresh tokens
|
|
4. **Multi-Factor Authentication**: Add MFA support for admin accounts
|
|
5. **API Key Authentication**: Support for API access with keys
|
|
6. **Permission Caching**: Cache permission checks for performance
|
|
7. **Dynamic Permissions**: Database-driven permission system
|
|
|
|
## Troubleshooting
|
|
|
|
### Common Issues
|
|
|
|
1. **Redirect Loops**: Check for circular redirects in auth logic
|
|
2. **Session Expiry**: Ensure proper session renewal
|
|
3. **Permission Denied**: Verify user auth level and status
|
|
4. **Inactive Users**: Check user status in database
|
|
|
|
### Debug Information
|
|
|
|
Enable debug logging by setting environment variables:
|
|
```bash
|
|
DEBUG=auth:*
|
|
LOG_LEVEL=debug
|
|
```
|
|
|
|
This will provide detailed information about authentication and authorization decisions. |