# Permission-Based Navigation System - Production Deployment

This document describes the production deployment script for the permission-based navigation system that dynamically shows/hides navigation items based on user access permissions.

## Overview

The permission-based navigation system ensures that when users don't have "Access" permission for a module, the corresponding navigation item is completely hidden from both desktop and mobile sidebars. This provides a clean, intuitive user experience where users only see what they can access.

## Features

- **Dynamic Navigation**: Navigation items appear/disappear based on user permissions
- **Template Filters**: Custom Django template filters for permission checking
- **View-Level Security**: Decorators to prevent direct URL access
- **Mobile Support**: Both desktop and mobile navigation are permission-controlled
- **Production Ready**: Comprehensive error handling, logging, and rollback capability
- **Non-Interactive**: Fully automated deployment script

## Files Modified

1. **`users/templatetags/permission_filters.py`** - Template filters for permission checking
2. **`templates/base.html`** - Updated navigation with conditional rendering
3. **`users/decorators.py`** - Added module access decorator for view protection

## Deployment Script Usage

### Basic Deployment

```bash
# Deploy with automatic backup
python deploy_permission_navigation.py

# Test deployment without making changes
python deploy_permission_navigation.py --dry-run

# Deploy to specific project directory
python deploy_permission_navigation.py --project-root /path/to/your/django/project
```

### Rollback

```bash
# Rollback to previous version
python deploy_permission_navigation.py --rollback
```

### Command Line Options

- `--dry-run`: Show what would be done without making changes
- `--backup`: Create backup before deployment (default: True)
- `--rollback`: Rollback to previous version
- `--project-root`: Path to Django project root (default: current directory)

## How It Works

### 1. Template Filter

The `has_module_access` template filter checks if a user has access permission for a specific module:

```django
{% if user|has_module_access:'dashboard' %}
    <!-- Navigation item for Dashboard -->
{% endif %}
```

### 2. Permission Checking Logic

```python
def has_permission(self, module, action):
    """Check if user has permission for a specific module and action"""
    if self.role == 'admin':
        return True  # Admin has all permissions
    
    # Check custom user permissions first
    # Fall back to role permissions
    # Return False if no permission found
```

### 3. Navigation Rendering

Navigation items are conditionally rendered based on permissions:

```django
<!-- Before: Always visible -->
<li><a href="{% url 'dashboard' %}">Dashboard</a></li>

<!-- After: Permission-controlled -->
{% if user|has_module_access:'dashboard' %}
<li><a href="{% url 'dashboard' %}">Dashboard</a></li>
{% endif %}
```

## Modules Covered

The following navigation items are now permission-controlled:

| Module | Navigation Item | Permission Check |
|--------|----------------|------------------|
| `dashboard` | Dashboard | `user|has_module_access:'dashboard'` |
| `clients` | Clients | `user|has_module_access:'clients'` |
| `loans` | Loans | `user|has_module_access:'loans'` |
| `repayments` | All Repayments | `user|has_module_access:'repayments'` |
| `portfolio` | Portfolio | `user|has_module_access:'portfolio'` |
| `reports_statements` | Reports & Statements | `user|has_module_access:'reports_statements'` |
| `documents` | Documents | `user|has_module_access:'documents'` |
| `customer_documents` | Customer Documents | `user|has_module_access:'customer_documents'` |
| `payment_receipts` | Payment Receipts | `user|has_module_access:'payment_receipts'` |
| `notifications` | Notifications | `user|has_module_access:'notifications'` |
| `settings` | Settings (General) | `user|has_module_access:'settings'` |
| `branch_settings` | Branch Settings | `user|has_module_access:'branch_settings'` |
| `system_settings` | System Settings | `user|has_module_access:'system_settings'` |

## Testing the Implementation

### 1. Deploy the System

```bash
python deploy_permission_navigation.py --dry-run  # Test first
python deploy_permission_navigation.py            # Deploy
```

### 2. Test Permission Changes

1. Go to **Staff Management** → Select a user → **User Permissions**
2. **Uncheck the "Access" checkbox** for any module (e.g., "Reports & Statements")
3. **Save the permissions**
4. **Log in as that user** - the navigation item should be completely hidden

### 3. Verify Security

Try accessing the URL directly (e.g., `/reports/`) - users without permission should be redirected with an error message.

## Production Considerations

### 1. Backup Strategy

The deployment script automatically creates backups in the `backups/` directory:

```
backups/
└── permission_nav_YYYYMMDD_HHMMSS/
    ├── permission_filters.py
    ├── base.html
    └── decorators.py
```

### 2. Logging

All deployment activities are logged to:
- Console output
- `permission_navigation_deployment.log` file

### 3. Error Handling

The script includes comprehensive error handling:
- Project structure validation
- File existence checks
- Rollback capability
- Detailed logging

### 4. Performance Impact

The permission checks are lightweight and cached by Django's template system. The impact on page load times is minimal.

## Troubleshooting

### Common Issues

1. **Template not found errors**
   - Ensure you're running the script from the correct Django project directory
   - Use `--project-root` to specify the correct path

2. **Permission checks not working**
   - Verify that the `permission_filters` template tag is loaded in your templates
   - Check that user permissions are properly set in the database

3. **Navigation items still visible**
   - Clear browser cache
   - Restart Django development server
   - Check that the template changes were applied correctly

### Rollback Process

If issues occur, rollback immediately:

```bash
python deploy_permission_navigation.py --rollback
```

This will restore all files to their previous state using the automatic backup.

## Security Notes

1. **View-Level Protection**: The `module_access_required` decorator provides additional security for direct URL access
2. **Admin Override**: Admin users always have access to all modules
3. **Permission Hierarchy**: Custom user permissions override role permissions
4. **Expired Permissions**: Time-based permissions are automatically checked

## Maintenance

### Regular Tasks

1. **Monitor Logs**: Check deployment logs for any issues
2. **Test Permissions**: Regularly verify that permission changes work as expected
3. **Update Permissions**: Use the existing permission management interface to modify user access

### Future Enhancements

The system is designed to be extensible:
- Add new modules by updating the template filter
- Implement more granular permissions
- Add permission-based feature toggles

## Support

For issues or questions:
1. Check the deployment logs
2. Verify project structure and file permissions
3. Test with `--dry-run` first
4. Use rollback if needed

---

**Note**: This deployment script is production-ready and includes comprehensive error handling, logging, and rollback capabilities. Always test with `--dry-run` first in production environments.
