# Deywuro Sender ID API - Technical Administration Guide

## Overview

This guide is intended for technical administrators responsible for managing the Sender ID API, including API key management, IP whitelisting, and system maintenance.

## System Architecture

The Sender ID API consists of:
- PHP-based RESTful API server
- Two MySQL databases:
  - Primary Deywuro database (existing user data)
  - API-specific database (request tracking, API keys, whitelisting)

## Database Configuration

Database connection settings are stored in `config/config.php`. When deploying to production, ensure:
- Secure database credentials
- Limited database user privileges
- Proper network security between API and database servers

### Primary Database Schema Modifications

The following modifications have been made to the existing Deywuro database:

```sql
ALTER TABLE user_sender_ids 
ADD COLUMN request_id VARCHAR(64) NULL COMMENT 'Request ID for API requests',
ADD COLUMN api_client_id VARCHAR(64) NULL COMMENT 'API client ID',
ADD COLUMN ip_address VARCHAR(45) NULL COMMENT 'Client IP address',
ADD INDEX (request_id),
ADD INDEX (api_client_id);
```

### API Database Schema

The API database includes the following tables:
- `api_clients`: Stores client information
- `api_keys`: Stores API keys associated with clients
- `ip_whitelist`: Stores whitelisted IP addresses
- `sender_id_requests`: Tracks sender ID requests made through the API
- `rate_limits`: Tracks API usage for rate limiting

## API Key Management

### Creating a New Client

1. Connect to the API database
2. Insert a new record into the `api_clients` table:

```sql
INSERT INTO api_clients (name, email, contact_person, phone, created_at, updated_at)
VALUES ('Client Name', 'contact@example.com', 'Contact Person', '+233123456789', NOW(), NOW());
```

### Generating an API Key

API keys can be generated through the API or directly in the database:

#### Method 1: Using the API (Authenticated as Admin)

```
POST /keys/generate
Content-Type: application/json
Authorization: Bearer ADMIN_API_KEY

{
    "client_id": "client_id_string",
    "expiry_date": "2026-12-31" // Optional
}
```

#### Method 2: Direct Database Insertion

```sql
INSERT INTO api_keys (client_id, api_key, is_active, created_at, updated_at, expires_at)
VALUES (
    'client_id_string',
    CONCAT('test_', SUBSTRING(MD5(RAND()), 1, 32)),
    1,
    NOW(),
    NOW(),
    DATE_ADD(NOW(), INTERVAL 1 YEAR)
);
```

### Revoking an API Key

To revoke an API key:

```sql
UPDATE api_keys SET is_active = 0, updated_at = NOW() WHERE api_key = 'key_to_revoke';
```

### Listing All API Keys

```sql
SELECT ak.api_key, ak.is_active, ak.created_at, ak.expires_at, ac.name as client_name
FROM api_keys ak
JOIN api_clients ac ON ak.client_id = ac.id
ORDER BY ak.created_at DESC;
```

## IP Whitelisting

### Adding an IP to Whitelist

#### Method 1: Using the API (Authenticated as Admin or Client)

```
POST /whitelist/add
Content-Type: application/json
Authorization: Bearer API_KEY

{
    "ip_address": "192.168.1.1",
    "description": "Office IP" // Optional
}
```

#### Method 2: Direct Database Insertion

```sql
INSERT INTO ip_whitelist (client_id, ip_address, description, created_at, updated_at)
VALUES ('client_id_string', '192.168.1.1', 'Office IP', NOW(), NOW());
```

### Removing an IP from Whitelist

```sql
DELETE FROM ip_whitelist WHERE client_id = 'client_id_string' AND ip_address = '192.168.1.1';
```

### Listing All Whitelisted IPs for a Client

```sql
SELECT ip_address, description, created_at 
FROM ip_whitelist 
WHERE client_id = 'client_id_string'
ORDER BY created_at DESC;
```

## Configuration Files

### Main Config File

Located at `config/config.php`, this file contains all system settings:

```php
// API Configuration
define('API_VERSION', 'v1');
define('API_BASE_URL', 'https://api.deywuro.com/' . API_VERSION);

// Database Configuration
define('PRIMARY_DB_HOST', 'primary_db_host');
define('PRIMARY_DB_PORT', 3306);
define('PRIMARY_DB_USER', 'db_user');
define('PRIMARY_DB_PASS', 'db_password');
define('PRIMARY_DB_NAME', 'db_name');

// API Database Configuration
define('API_DB_HOST', 'api_db_host');
define('API_DB_PORT', 3306);
define('API_DB_USER', 'api_db_user');
define('API_DB_PASS', 'api_db_password');
define('API_DB_NAME', 'api_db_name');

// Rate Limiting Configuration
define('RATE_LIMIT_HOUR', 100);
define('RATE_LIMIT_DAY', 1000);
```

## Server Setup

### Apache Configuration

Create a virtual host in Apache:

```apache
<VirtualHost *:80>
    ServerName api.deywuro.com
    DocumentRoot /path/to/sender-id-api
    
    <Directory /path/to/sender-id-api>
        AllowOverride All
        Require all granted
        Options -Indexes +FollowSymLinks
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/api-error.log
    CustomLog ${APACHE_LOG_DIR}/api-access.log combined
</VirtualHost>
```

Create a `.htaccess` file in the root directory:

```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
```

### Nginx Configuration

```nginx
server {
    listen 80;
    server_name api.deywuro.com;
    root /path/to/sender-id-api;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}
```

## Cron Jobs

### Status Change Notification Cron Job

Create a file `crons/status_check.php` with the following content:

```php
<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../utilities/Logger.php';

// This script checks for status changes in sender IDs and sends SMS notifications

// Connect to databases
$db = Database::getPrimaryConnection();
$apiDb = Database::getApiConnection();

// Get sender IDs with status changes
$query = "
    SELECT si.id, si.user_id, si.sender_id, si.status, si.comment, sir.request_id, u.phone_number, u.username
    FROM user_sender_ids si
    JOIN sender_id_requests sir ON si.id = sir.deywuro_id
    JOIN users u ON si.user_id = u.id
    WHERE si.updated_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)
    AND (si.status = 1 OR si.status = 2)
    AND sir.notification_sent = 0
";

$result = $db->query($query);

while ($row = $result->fetch_assoc()) {
    $status = $row['status'] == 1 ? 'APPROVED' : 'REJECTED';
    $message = "Your Sender ID '{$row['sender_id']}' has been {$status}";
    
    if ($row['status'] == 2 && !empty($row['comment'])) {
        $message .= ". Reason: {$row['comment']}";
    }
    
    // Send SMS notification
    $smsUrl = SMS_API_URL;
    $smsData = [
        'username' => SMS_USERNAME,
        'password' => SMS_PASSWORD,
        'source' => SMS_SOURCE,
        'destination' => $row['phone_number'],
        'message' => $message
    ];
    
    $ch = curl_init($smsUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($smsData));
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    // Mark notification as sent
    $updateStmt = $apiDb->prepare("
        UPDATE sender_id_requests 
        SET notification_sent = 1, updated_at = NOW() 
        WHERE request_id = ?
    ");
    $updateStmt->bind_param("s", $row['request_id']);
    $updateStmt->execute();
    $updateStmt->close();
    
    // Log the notification
    Logger::log(Logger::INFO, "Sender ID status notification sent", [
        'sender_id' => $row['sender_id'],
        'user' => $row['username'],
        'status' => $status,
        'phone' => $row['phone_number']
    ]);
}
```

Add this to your crontab to run every 5 minutes:

```
*/5 * * * * php /path/to/sender-id-api/crons/status_check.php >> /path/to/logs/cron.log 2>&1
```

## Monitoring and Maintenance

### Logs

Logs are stored in the `logs` directory. Key log files:
- `api.log`: General API activity
- `error.log`: Errors and exceptions
- `auth.log`: Authentication attempts
- `rate_limit.log`: Rate limit events

### Backup Procedures

1. **Database Backups**

   Daily backup of both databases:
   ```bash
   mysqldump -h PRIMARY_DB_HOST -u PRIMARY_DB_USER -p PRIMARY_DB_NAME user_sender_ids > /path/to/backups/user_sender_ids_$(date +\%Y\%m\%d).sql
   
   mysqldump -h API_DB_HOST -u API_DB_USER -p API_DB_NAME > /path/to/backups/api_db_$(date +\%Y\%m\%d).sql
   ```

2. **Log Rotation**

   Configure log rotation to prevent logs from growing too large:
   ```
   /path/to/sender-id-api/logs/*.log {
       daily
       missingok
       rotate 7
       compress
       delaycompress
       notifempty
       create 0640 www-data www-data
   }
   ```

## Security Best Practices

1. **API Key Management**
   - Rotate API keys regularly
   - Use expiry dates for temporary access
   - Implement key rotation procedures

2. **IP Whitelisting**
   - Verify IP addresses before whitelisting
   - Document purpose of each whitelisted IP
   - Regularly review and clean up the whitelist

3. **Access Control**
   - Limit database access to only necessary privileges
   - Use separate accounts for API and admin interfaces
   - Implement access logs and audit trails

4. **Rate Limiting**
   - Monitor for abuse patterns
   - Adjust rate limits based on client needs
   - Implement client-specific limits when necessary

5. **Error Handling**
   - Ensure errors don't leak sensitive information
   - Log detailed errors internally
   - Return sanitized error messages to clients

## Troubleshooting

### Common Issues

1. **API Key Authentication Failures**
   - Check if key is active in the database
   - Verify key hasn't expired
   - Check if key is being sent correctly in the Authorization header

2. **IP Whitelist Issues**
   - Verify client's actual IP against whitelisted IPs
   - Check for proxy or NAT configurations
   - Consider IPv4 vs IPv6 concerns

3. **Database Connection Errors**
   - Verify connection parameters
   - Check network connectivity
   - Ensure user has proper privileges

4. **High Rate of Failed Requests**
   - Check rate limiting logs
   - Review error logs for recurring patterns
   - Analyze client usage patterns

### Support Procedures

For any issues that require additional support:

1. Collect relevant log entries
2. Document the issue with steps to reproduce
3. Gather client information (ID, affected API key)
4. Contact the development team at dev@deywuro.com 