# System Logs & Security Documentation

## Overview

The SSWSEEP Components application now includes a comprehensive system logging and security monitoring system. This system tracks all user activities, login attempts, and provides security features like account lockouts.

## Features

### 1. System Logs
- **Automatic Activity Logging**: All user actions (create, update, delete, export) are automatically tracked
- **Login/Logout Tracking**: Every successful login and logout is recorded
- **Module-based Organization**: Logs are categorized by component (admin, component1, component2, etc.)
- **IP and User Agent Tracking**: Security information is captured for each activity
- **Advanced Filtering**: Filter logs by user, action, module, date ranges

### 2. Login Security
- **5-Attempt Lockout**: After 5 failed login attempts, user accounts are automatically locked for 60 minutes
- **Lockout Message**: Users see "You have been locked out after 5 unsuccessful attempts! Contact the System Administrator for help."
- **Admin Unlock**: Administrators can manually unlock users and reset their passwords
- **Real-time Monitoring**: Live view of login attempts and locked accounts

## Access Points

### Admin Dashboard
1. Log in as a Super Admin
2. Navigate to the Admin Dashboard
3. Click the "System Logs" button in the Quick Actions section

### Direct URLs
- **System Logs**: `/admin/system-logs`
- **Login Attempts**: `/admin/login-attempts`

## System Logs Interface

### Features
- **Filterable View**: Filter by user, action, module, or date range
- **Pagination**: 50 logs per page for optimal performance
- **Action Badges**: Color-coded badges for different action types
- **User Information**: Shows which user performed each action
- **IP Tracking**: Displays IP addresses for security monitoring

### Action Types
- `login` - User login (Green badge)
- `logout` - User logout (Yellow badge)
- `create` - Data creation (Blue badge)
- `update` - Data modification (Light blue badge)
- `delete` - Data deletion (Red badge)
- `export` - Data export (Purple badge)
- `unlock_user` - Admin unlock action (Orange badge)

## Login Attempts Interface

### Features
- **Real-time Status**: Shows current lockout status
- **Success/Failure Indicators**: Clear visual indicators for login outcomes
- **Locked Accounts Alert**: Warning banner showing currently locked accounts
- **Unlock Functionality**: Direct access to unlock users
- **Advanced Filtering**: Filter by email, status, or date range

### Lockout Process
1. User fails login attempt 1-4: Attempts are logged
2. User fails login attempt 5: Account is locked for 60 minutes
3. User sees lockout message on next login attempt
4. Admin can unlock account via Login Attempts interface
5. Admin can reset user password during unlock process

## Manual Logging

### Using SystemLogService
You can manually log activities throughout your application using the `SystemLogService`:

```php
use App\Services\SystemLogService;

// Log user management actions
SystemLogService::logUserManagement('create_user', 'Created new user: John Doe');

// Log data operations
SystemLogService::logCreate($model, 'component1');
SystemLogService::logUpdate($model, 'component2');
SystemLogService::logDelete($model, 'component3');

// Log exports
SystemLogService::logExport('Exported seedlab beneficiaries to Excel', 'component2');

// Log security events
SystemLogService::logSecurity('account_locked', 'Account locked due to failed attempts');
```

### Direct Model Usage
```php
use App\Models\SystemLog;

SystemLog::create([
    'user_id' => auth()->id(),
    'action' => 'custom_action',
    'description' => 'Custom activity description',
    'ip_address' => request()->ip(),
    'user_agent' => request()->userAgent(),
    'module' => 'custom_module',
]);
```

## Database Tables

### system_logs
- `id` - Primary key
- `user_id` - Foreign key to users table (nullable)
- `action` - Action type (login, create, update, etc.)
- `description` - Detailed description of the activity
- `ip_address` - User's IP address
- `user_agent` - Browser user agent string
- `module` - Application module (admin, component1, etc.)
- `loggable_id` - Polymorphic relation ID (nullable)
- `loggable_type` - Polymorphic relation type (nullable)
- `created_at` - Timestamp
- `updated_at` - Timestamp

### login_attempts
- `id` - Primary key
- `email` - Email address used for login attempt
- `ip_address` - IP address of the attempt
- `user_agent` - Browser user agent string
- `successful` - Boolean indicating success/failure
- `locked_until` - Timestamp when lockout expires (nullable)
- `created_at` - Timestamp
- `updated_at` - Timestamp

## Security Considerations

### Data Privacy
- IP addresses and user agents are stored for security monitoring
- Consider data retention policies for log data
- Logs contain sensitive user activity information

### Performance
- Logs are paginated to prevent performance issues
- Consider archiving old logs periodically
- Database indexes are optimized for common queries

### Access Control
- Only Super Admins can access system logs
- Login attempt monitoring is restricted to administrators
- Regular users cannot view security logs

## Troubleshooting

### Common Issues

1. **No logs appearing**
   - Check if the LogUserActivity middleware is properly registered
   - Verify user is authenticated
   - Ensure routes are properly configured

2. **Login lockout not working**
   - Verify LoginAttempt model is properly configured
   - Check if login controller is updated with tracking code
   - Ensure database migrations have been run

3. **Performance issues**
   - Consider adding database indexes for frequently queried fields
   - Implement log archiving for old records
   - Use pagination for large log datasets

### Testing Data
Use the provided seeders to populate sample data:
```bash
php artisan db:seed --class=SystemLogSeeder
php artisan db:seed --class=LoginAttemptSeeder
```

## Future Enhancements

### Potential Improvements
1. **Log Archiving**: Automatic archiving of old logs
2. **Email Notifications**: Alerts for suspicious activities
3. **Dashboard Widgets**: Real-time security metrics
4. **Export Functionality**: Export logs for analysis
5. **API Integration**: External security monitoring
6. **Advanced Analytics**: Security pattern recognition

### Maintenance
- Regular database maintenance for log tables
- Monitor disk space usage for log storage
- Review and update retention policies
- Periodic security audit of logged activities

## Support

For issues or questions about the system logs functionality:
1. Check this documentation first
2. Review the error logs in Laravel
3. Verify database connections and migrations
4. Test with sample data using provided seeders
