# Security & Audit Module

## Overview

The Security & Audit module provides comprehensive security features including two-factor authentication, audit logging, security monitoring, IP whitelisting, and compliance tracking.

---

## Features

### Core Functionality
- ✅ Two-Factor Authentication (2FA)
- ✅ Comprehensive audit logging
- ✅ Security event monitoring
- ✅ IP address whitelisting
- ✅ Login attempt tracking
- ✅ Session management
- ✅ Password policies
- ✅ Data encryption
- ✅ Security reports and alerts
- ✅ Compliance tracking
- ✅ User activity monitoring

---

## Two-Factor Authentication (2FA)

### Overview

Two-Factor Authentication adds an extra layer of security by requiring users to provide two forms of identification:
1. Something they know (password)
2. Something they have (mobile device with authenticator app)

### 2FA Setup Process

**For Users**:
```
1. Navigate to Profile → Security
2. Click "Enable Two-Factor Authentication"
3. Scan QR code with authenticator app
   (Google Authenticator, Authy, Microsoft Authenticator)
4. Enter verification code from app
5. Save recovery codes securely
6. 2FA enabled
```

**QR Code Display**:
```
┌─────────────────────────────────────┐
│ Scan this QR code with your         │
│ authenticator app                    │
│                                      │
│  ┌─────────────────────────────┐   │
│  │                              │   │
│  │      [QR CODE IMAGE]         │   │
│  │                              │   │
│  └─────────────────────────────┘   │
│                                      │
│ Or enter this code manually:        │
│ ABCD EFGH IJKL MNOP QRST UVWX      │
│                                      │
│ Enter verification code:            │
│ [______]                            │
│                                      │
│ [Verify and Enable]                 │
└─────────────────────────────────────┘
```

### Recovery Codes

**Purpose**: Backup access if authenticator app is unavailable

**Features**:
- 10 single-use recovery codes generated
- Can be used instead of 2FA code
- New codes can be regenerated
- Secure storage recommended

**Recovery Codes Display**:
```
┌─────────────────────────────────────┐
│ Recovery Codes                       │
│ Save these codes in a secure place  │
├─────────────────────────────────────┤
│ 1. ABCD-EFGH-IJKL                   │
│ 2. MNOP-QRST-UVWX                   │
│ 3. YZAB-CDEF-GHIJ                   │
│ 4. KLMN-OPQR-STUV                   │
│ 5. WXYZ-ABCD-EFGH                   │
│ 6. IJKL-MNOP-QRST                   │
│ 7. UVWX-YZAB-CDEF                   │
│ 8. GHIJ-KLMN-OPQR                   │
│ 9. STUV-WXYZ-ABCD                   │
│ 10. EFGH-IJKL-MNOP                  │
├─────────────────────────────────────┤
│ [Download] [Print] [Copy]           │
│ [Generate New Codes]                │
└─────────────────────────────────────┘
```

### 2FA Login Flow

```
1. User enters email and password
2. System validates credentials
3. If 2FA enabled:
   a. Redirect to 2FA verification page
   b. User enters 6-digit code from app
   c. System validates code
   d. Grant access if valid
4. If 2FA not enabled:
   a. Grant access immediately
```

### 2FA Management

**Admin Controls**:
- Enforce 2FA for all users
- Enforce 2FA for specific roles
- Reset user's 2FA
- View 2FA adoption rate
- Generate compliance reports

---

## Audit Logging

### What is Logged

**User Actions**:
- Login/Logout
- Password changes
- Profile updates
- 2FA enable/disable
- Permission changes
- Role assignments

**Data Changes**:
- Employee records (create/update/delete)
- Payroll modifications
- Leave approvals/rejections
- Attendance modifications
- Settings changes

**Security Events**:
- Failed login attempts
- Account lockouts
- Password reset requests
- Suspicious activities
- IP address changes

**System Events**:
- Database backups
- System updates
- Configuration changes
- Maintenance activities

### Audit Log Structure

**Log Entry**:
```json
{
  "id": 12345,
  "user_id": 1,
  "user_name": "John Doe",
  "user_email": "john.doe@example.com",
  "organization_id": 1,
  "action": "update",
  "model": "Employee",
  "model_id": 42,
  "changes": {
    "old": {
      "basic_salary": 80000
    },
    "new": {
      "basic_salary": 85000
    }
  },
  "ip_address": "192.168.1.100",
  "user_agent": "Mozilla/5.0...",
  "timestamp": "2024-02-15 10:30:45",
  "description": "Updated employee salary"
}
```

### Audit Log Viewer

**Access**: Security → Audit Logs

**Features**:
```
┌─────────────────────────────────────────────────┐
│ Audit Logs                                       │
├─────────────────────────────────────────────────┤
│ Filters:                                         │
│ [User] [Action] [Model] [Date Range] [Search]  │
├─────────────────────────────────────────────────┤
│ Date/Time         User      Action    Details   │
├─────────────────────────────────────────────────┤
│ 2024-02-15 10:30  John Doe  Update    Employee  │
│ Changed salary from 80,000 to 85,000           │
│ IP: 192.168.1.100                               │
├─────────────────────────────────────────────────┤
│ 2024-02-15 09:15  Jane Smith Login    Success   │
│ 2FA verified                                    │
│ IP: 192.168.1.105                               │
├─────────────────────────────────────────────────┤
│ 2024-02-15 08:45  Bob Johnson Approve  Leave    │
│ Approved leave request #123                     │
│ IP: 192.168.1.110                               │
└─────────────────────────────────────────────────┘

[Export to CSV] [Export to PDF]
```

---

## Security Monitoring

### Real-Time Monitoring

**Monitored Activities**:
1. **Login Attempts**
   - Successful logins
   - Failed login attempts
   - Account lockouts
   - Unusual login times
   - New device logins

2. **Data Access**
   - Sensitive data access
   - Bulk data exports
   - Unusual query patterns
   - Unauthorized access attempts

3. **System Changes**
   - Configuration modifications
   - Permission changes
   - User role updates
   - Security setting changes

### Security Alerts

**Alert Types**:

1. **Critical Alerts**
   - Multiple failed login attempts
   - Unauthorized access attempts
   - Data breach indicators
   - System compromise signs

2. **Warning Alerts**
   - Unusual activity patterns
   - Policy violations
   - Expired passwords
   - Inactive 2FA

3. **Info Alerts**
   - New user registrations
   - Password changes
   - Profile updates
   - Normal security events

**Alert Notification**:
```
Subject: Security Alert - Multiple Failed Login Attempts

Alert Level: WARNING
Time: 2024-02-15 10:45:30
User: john.doe@example.com
IP Address: 192.168.1.100

Details:
5 failed login attempts detected within 10 minutes.
Account has been temporarily locked for 30 minutes.

Actions Taken:
- Account locked
- User notified via email
- Security team alerted

Recommended Actions:
- Verify user identity
- Check for password compromise
- Review recent activity

[View Full Details] [Unlock Account]
```

---

## IP Whitelisting

### Overview

IP Whitelisting restricts system access to specific IP addresses or ranges, adding an extra security layer.

### IP Whitelist Management

**Access**: Security → IP Whitelist

**Features**:
```
┌─────────────────────────────────────────────┐
│ IP Whitelist Management                      │
├─────────────────────────────────────────────┤
│ [Add IP Address] [Add IP Range]             │
├─────────────────────────────────────────────┤
│ IP Address/Range    Description    Actions  │
├─────────────────────────────────────────────┤
│ 192.168.1.0/24     Office Network  [Remove] │
│ 41.90.x.x          Kenya IPs       [Remove] │
│ 197.248.x.x        ISP Range       [Remove] │
│ 10.0.0.100         VPN Gateway     [Remove] │
└─────────────────────────────────────────────┘

Current IP: 192.168.1.100 ✓ Whitelisted
```

**Add IP Form**:
```
Add IP to Whitelist

IP Address/Range: [____________]
Description: [____________]
Expiry Date: [Optional]
Active: [✓]

[Add to Whitelist] [Cancel]
```

### IP Whitelist Rules

**Configuration**:
- Enable/disable IP whitelisting
- Allow/block specific IPs
- Set IP ranges
- Temporary access grants
- Emergency bypass codes

---

## Password Policies

### Policy Configuration

**Access**: Security → Password Policies

**Settings**:
```
Password Requirements:
☑ Minimum length: [8] characters
☑ Require uppercase letters
☑ Require lowercase letters
☑ Require numbers
☑ Require special characters
☑ Prevent common passwords
☑ Prevent password reuse (last [5] passwords)

Password Expiry:
☑ Passwords expire after [90] days
☑ Warning [7] days before expiry
☑ Force change on first login

Account Lockout:
☑ Lock account after [5] failed attempts
☑ Lockout duration: [30] minutes
☑ Notify user of lockout

[Save Settings]
```

### Password Strength Indicator

**During Password Creation**:
```
New Password: [••••••••••]

Strength: ████████░░ Strong

Requirements:
✓ At least 8 characters
✓ Contains uppercase letter
✓ Contains lowercase letter
✓ Contains number
✓ Contains special character
✗ Not a common password
```

---

## Session Management

### Session Configuration

**Settings**:
```
Session Timeout: [120] minutes
Remember Me Duration: [30] days
Maximum Concurrent Sessions: [3]
Force Logout on Password Change: [✓]
Secure Cookies: [✓]
HTTP Only Cookies: [✓]
```

### Active Sessions

**User View**:
```
┌─────────────────────────────────────────────┐
│ Active Sessions                              │
├─────────────────────────────────────────────┤
│ Device          Location      Last Active   │
├─────────────────────────────────────────────┤
│ Chrome/Windows  Nairobi, KE   2 min ago     │
│ (Current)                     [Logout]      │
├─────────────────────────────────────────────┤
│ Safari/iPhone   Mombasa, KE   1 hour ago    │
│                               [Logout]      │
├─────────────────────────────────────────────┤
│ Firefox/Linux   Kisumu, KE    2 days ago    │
│                               [Logout]      │
└─────────────────────────────────────────────┘

[Logout All Other Sessions]
```

---

## Data Encryption

### Encryption Methods

1. **Data at Rest**
   - Database encryption
   - File storage encryption
   - Backup encryption

2. **Data in Transit**
   - HTTPS/TLS encryption
   - Secure API communication
   - Encrypted email

3. **Sensitive Fields**
   - Password hashing (bcrypt)
   - 2FA secrets encryption
   - Recovery codes encryption
   - Personal data encryption

---

## Security Reports

### Available Reports

1. **Security Dashboard**
   ```
   ┌─────────────────────────────────────┐
   │ Security Overview                    │
   ├─────────────────────────────────────┤
   │ 2FA Adoption: 75% (45/60 users)     │
   │ Failed Logins (24h): 12             │
   │ Locked Accounts: 2                  │
   │ Active Sessions: 38                 │
   │ Security Alerts: 3                  │
   └─────────────────────────────────────┘
   ```

2. **Login Activity Report**
   - Successful logins
   - Failed attempts
   - Login times and patterns
   - Geographic distribution

3. **User Activity Report**
   - Actions per user
   - Data access patterns
   - Modification history
   - Suspicious activities

4. **Compliance Report**
   - 2FA compliance
   - Password policy compliance
   - Access control compliance
   - Audit trail completeness

5. **Security Incident Report**
   - Incident timeline
   - Affected users/data
   - Response actions
   - Resolution status

---

## Compliance Features

### GDPR Compliance

**Features**:
- Data access requests
- Data export functionality
- Right to be forgotten
- Consent management
- Data processing records

### Data Protection

**Measures**:
- Role-based access control
- Data minimization
- Purpose limitation
- Storage limitation
- Integrity and confidentiality

---

## Security Best Practices

### For System Administrators

1. **Regular Security Audits**
   - Review audit logs weekly
   - Monitor failed login attempts
   - Check for unusual patterns
   - Update security policies

2. **Access Control**
   - Implement least privilege
   - Regular permission reviews
   - Remove inactive users
   - Monitor privileged access

3. **Incident Response**
   - Have response plan
   - Document incidents
   - Learn from incidents
   - Update procedures

### For Users

1. **Password Security**
   - Use strong passwords
   - Don't share passwords
   - Change regularly
   - Use password manager

2. **2FA Usage**
   - Enable 2FA
   - Secure recovery codes
   - Update authenticator app
   - Report lost devices

3. **Awareness**
   - Recognize phishing
   - Report suspicious activity
   - Lock screen when away
   - Use secure networks

---

## Security Incident Response

### Incident Response Plan

**Steps**:
```
1. Detection
   - Identify security incident
   - Assess severity
   - Document details

2. Containment
   - Isolate affected systems
   - Prevent further damage
   - Preserve evidence

3. Investigation
   - Analyze logs
   - Identify root cause
   - Determine impact

4. Remediation
   - Fix vulnerabilities
   - Restore systems
   - Update security measures

5. Recovery
   - Resume normal operations
   - Monitor for recurrence
   - Verify security

6. Post-Incident
   - Document lessons learned
   - Update procedures
   - Train staff
   - Improve defenses
```

---

## Permissions

### Required Permissions

| Action | Permission | Description |
|--------|-----------|-------------|
| View Security Dashboard | `view_security_dashboard` | Access security overview |
| View Audit Logs | `view_audit_logs` | Access audit trail |
| Manage IP Whitelist | `manage_ip_whitelist` | Configure IP restrictions |
| Manage Security Settings | `manage_security_settings` | Configure security policies |
| Reset User 2FA | `reset_user_2fa` | Reset 2FA for users |
| View Security Reports | `view_security_reports` | Access security reports |
| Manage Security Incidents | `manage_security_incidents` | Handle security incidents |

---

## Troubleshooting

### Common Issues

**Issue**: Cannot login with 2FA
- **Solution**: Use recovery code, contact admin to reset 2FA

**Issue**: Account locked
- **Solution**: Wait for lockout period, contact admin for unlock

**Issue**: IP blocked
- **Solution**: Contact admin to whitelist IP

**Issue**: Audit logs not showing
- **Solution**: Check permissions, verify date range

---

## Future Enhancements

- [ ] Biometric authentication
- [ ] Advanced threat detection
- [ ] Security information and event management (SIEM)
- [ ] Automated incident response
- [ ] Machine learning for anomaly detection
- [ ] Integration with security tools
- [ ] Advanced compliance reporting
- [ ] Security awareness training module

---

**Last Updated**: February 2026
