# API Security Implementation Guide

## Usage in API Endpoints

Add this code at the beginning of each API endpoint:

```php
<?php
require_once 'src/includes/APISecurityConfig.php';
require_once 'src/includes/RateLimiter.php';

// Apply security measures
APISecurityConfig::setSecurityHeaders();
APISecurityConfig::enforceHTTPS();

// Rate limiting
$rateLimiter = new RateLimiter();
$clientId = RateLimiter::getClientIdentifier();
$endpoint = 'survey_stats'; // Change for each endpoint

$rateConfig = APISecurityConfig::RATE_LIMITS[$endpoint] ?? APISecurityConfig::RATE_LIMITS['general'];
$rateLimiter->checkLimit($clientId, $rateConfig['limit'], $rateConfig['window'], $endpoint);

// Input validation
try {
    $required = ['survey_id']; // Define required fields
    $optional = ['user_id'];   // Define optional fields
    
    $inputData = json_decode(file_get_contents('php://input'), true) ?? $_REQUEST;
    $validatedData = APISecurityConfig::validateInput($inputData, $required, $optional);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
    APISecurityConfig::logSecurityEvent('validation_failed', ['error' => $e->getMessage()]);
    exit;
}

// Continue with API logic using $validatedData
?>
```

## Security Features Implemented

1. **Input Validation**: All inputs sanitized and validated
2. **Rate Limiting**: Prevents API abuse (configurable per endpoint)
3. **HTTPS Enforcement**: Redirects to HTTPS in production
4. **Security Headers**: Prevents XSS, clickjacking, etc.
5. **CORS Configuration**: Proper cross-origin request handling
6. **Security Logging**: All security events logged for monitoring

## Configuration

Edit `APISecurityConfig.php` to adjust:
- Rate limits per endpoint
- Validation rules
- Allowed values for specific fields
- CORS origins

## Monitoring

Check security logs in `/logs/security/` for:
- Failed validation attempts
- Rate limit violations
- Suspicious activities
