# Logout Controller Documentation

**File**: `/controllers/logout.php`  
**Purpose**: User session termination and cleanup  
**Last Updated**: December 20, 2024  
**Total Functions**: 1  
**Lines of Code**: ~38

---

## 📋 Overview

The Logout Controller is a simple but critical security component that handles user session termination. It performs:
- User session cleanup
- Login status updates
- Cache file clearing
- Session destruction
- Redirection to login page

### Primary Functions
- [x] Clean user login status
- [x] Clear cached header files
- [x] Destroy user session
- [x] Redirect to login page

### Related Controllers
- [login.php](login.md) - Main authentication controller
- [userController.php](userController.md) - User management

---

## 🗄️ Database Tables

### Primary Tables (Indirect Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | User login tracking | userid, loginip, lastactivetime |

---

## 🔑 Key Functions

### 1. **Session Cleanup Process**
**Location**: Lines 26-37  
**Purpose**: Clean user session and logout safely

**Process Flow**:
1. **Start Session Management**:
   ```php
   session_start();
   ob_start();
   ```

2. **Load Required Classes**:
   - Connection classes
   - User DAO classes
   - Transaction management

3. **Update User Login Status**:
   ```php
   if (!empty($_SESSION['userid'])) {
       $myUserEx->removeUserIp($_SESSION['userid']);
   }
   ```

4. **Clear Cache Files**:
   ```php
   if (!empty($_SESSION['dbname']) && !empty($_SESSION['userid'])) {
       $fh = fopen('../temp__cashedheader/cashedheader_' . 
                   $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html', 'w');
       fclose($fh);
   }
   ```

5. **Destroy Session and Redirect**:
   ```php
   session_destroy();
   header("location:login.php");
   ```

---

## 🔄 Workflows

### Workflow 1: User Logout Process
```
┌─────────────────────────────────────────────────────────────┐
│                START: User Logout Request                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Initialize Session and Output Buffering                 │
│     - session_start()                                       │
│     - ob_start()                                            │
│     - Load required DAO classes                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Update User Login Status                                │
│     - Check if user session exists                          │
│     - Call removeUserIp() to clear login tracking          │
│     - Update user activity status in database              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Clear Cached Header Files                               │
│     - Check if cache identifiers exist                      │
│     - Clear user-specific cache file                        │
│     - Empty cache file contents                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Destroy Session and Redirect                            │
│     - Call session_destroy()                                │
│     - Clear all session variables                           │
│     - Redirect to login.php                                 │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| Direct access | Logout process | Terminate session and redirect to login |

**No URL parameters required** - Direct access triggers logout process

---

## 🔒 Security & Permissions

### Session Security
```php
// Proper session termination
session_start();  // Resume session to access variables
session_destroy(); // Destroy all session data
```

### User Tracking Cleanup
```php
// Clear user login tracking
$myUserEx->removeUserIp($_SESSION['userid']);
```

**Security Features**:
- Complete session destruction
- User login status cleanup
- Cache file clearing
- Automatic redirection

### Cache Security
```php
// Clear user-specific cache files
$cachePath = '../temp__cashedheader/cashedheader_' . 
             $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html';
$fh = fopen($cachePath, 'w');
fclose($fh); // Creates empty file
```

---

## 📊 Performance Considerations

### Efficiency Features
1. **Minimal Processing**: Only essential cleanup operations
2. **Quick Execution**: Simple linear process
3. **Resource Cleanup**: Proper file handle management
4. **Fast Redirection**: Immediate redirect to login

### Resource Management
```php
// Proper file handle cleanup
$fh = fopen($cacheFile, 'w');
fclose($fh); // Always close file handles
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Session Not Destroyed**
**Issue**: User remains logged in after logout  
**Cause**: session_destroy() not called or headers already sent

**Debug**:
```php
// Check if headers already sent
if (headers_sent()) {
    echo "Headers already sent - cannot destroy session";
}

// Verify session destruction
session_start();
if (empty($_SESSION)) {
    echo "Session successfully destroyed";
} else {
    echo "Session still active";
}
```

### 2. **Cache Files Not Cleared**
**Issue**: Old cache data persists after logout  
**Cause**: File permission issues or missing session variables

**Debug**:
```php
// Check session variables
if (empty($_SESSION['dbname']) || empty($_SESSION['userid'])) {
    echo "Session variables missing for cache cleanup";
}

// Check file permissions
$cacheDir = '../temp__cashedheader/';
if (!is_writable($cacheDir)) {
    echo "Cache directory not writable";
}
```

### 3. **Redirect Not Working**
**Issue**: Page doesn't redirect to login  
**Cause**: Headers already sent or output buffer issues

**Fix**:
```php
// Check output buffering
ob_start(); // Start output buffering before any output

// Clear any previous output
ob_clean();

// Perform redirect
header("Location: login.php");
exit(); // Always exit after redirect
```

### 4. **Database Update Failures**
**Issue**: User login status not updated in database  
**Cause**: Database connection issues or missing user ID

**Debug**:
```php
// Check user ID exists
if (empty($_SESSION['userid'])) {
    echo "User ID not found in session";
}

// Test database connection
try {
    $myUserEx->removeUserIp($_SESSION['userid']);
    echo "User status updated successfully";
} catch (Exception $e) {
    echo "Database update failed: " . $e->getMessage();
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Normal Logout
```
1. Login with valid credentials
2. Navigate to logout.php
3. Verify session destroyed
4. Confirm redirect to login
5. Attempt to access protected pages
6. Verify access denied
```

### Test Case 2: Multiple Logout Attempts
```
1. Login user
2. Logout once
3. Access logout.php again
4. Verify no errors
5. Confirm still redirects to login
```

### Test Case 3: Cache Cleanup Verification
```
1. Login and generate cached content
2. Check cache file exists and has content
3. Logout
4. Verify cache file is empty
5. Confirm no sensitive data in cache
```

### Test Case 4: Database Tracking Cleanup
```
1. Login and check user.loginip field
2. Verify IP address recorded
3. Logout
4. Check user.loginip cleared
5. Verify lastactivetime updated
```

---

## 🛡️ Security Best Practices

### Current Implementation
✅ **Good Practices**:
- Session destruction
- Cache cleanup
- Database status updates
- Immediate redirect

⚠️ **Missing Features**:
- CSRF token validation
- Secure cookie clearing
- Audit logging
- Browser cache headers

### Recommended Improvements
```php
// Enhanced logout with security headers
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

// Clear any authentication cookies
if (isset($_COOKIE['auth_token'])) {
    setcookie('auth_token', '', time() - 3600, '/', '', true, true);
}

// Log logout event for audit
error_log("User logout: ID {$_SESSION['userid']} at " . date('Y-m-d H:i:s'));
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [login.php](login.md) - Main authentication controller
- [userController.php](userController.md) - User management
- [usergroupController.php](usergroupController.md) - User group management

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Security Review**: ✅ Good basic implementation  
**Next Review**: When security enhancements are added