# Admin API Key Management

This document describes the enhanced API key management functionality that allows administrators to create and manage API keys for any user in the system.

## Overview

The VFX Project Management System now supports comprehensive API key management with different permission levels:

- **Developers**: Can create and manage their own API keys
- **Admins**: Can create and manage API keys for any user in the system

## Admin Capabilities

### 1. Create API Keys for Any User

Admins can create API keys for any approved user in the system using two methods:

#### Method 1: General Endpoint with user_id Parameter
```http
POST /auth/api-keys
Authorization: Bearer <admin_token>
Content-Type: application/json

{
  "name": "Integration Key for John Doe",
  "scopes": ["read:projects", "read:tasks"],
  "user_id": 123,
  "expires_at": "2024-12-31T23:59:59"
}
```

#### Method 2: Admin-Specific Endpoint
```http
POST /auth/admin/users/123/api-keys
Authorization: Bearer <admin_token>
Content-Type: application/json

{
  "name": "Integration Key for John Doe",
  "scopes": ["read:projects", "read:tasks"],
  "expires_at": "2024-12-31T23:59:59"
}
```

### 2. View All API Keys

Admins can view all API keys in the system:

```http
GET /auth/api-keys
Authorization: Bearer <admin_token>
```

Response includes user email for each API key:
```json
[
  {
    "id": 1,
    "user_id": 123,
    "user_email": "john.doe@example.com",
    "name": "Integration Key",
    "scopes": ["read:projects", "read:tasks"],
    "is_active": true,
    "expires_at": "2024-12-31T23:59:59Z",
    "last_used_at": "2024-01-15T10:30:00Z",
    "created_at": "2024-01-01T00:00:00Z"
  }
]
```

### 3. View API Keys for Specific User

```http
GET /auth/admin/users/123/api-keys
Authorization: Bearer <admin_token>
```

### 4. Manage Any API Key

Admins can update or delete any API key in the system:

```http
PUT /auth/api-keys/456
DELETE /auth/api-keys/456
Authorization: Bearer <admin_token>
```

### 5. View Usage Logs for Any API Key

```http
GET /auth/api-keys/456/usage
Authorization: Bearer <admin_token>
```

## API Key Scopes

Available scopes for API keys:

- `read:projects` - Read access to all projects
- `read:tasks` - Read access to all tasks
- `read:submissions` - Read access to all submissions
- `read:users` - Read access to user information
- `write:tasks` - Write access to tasks
- `write:submissions` - Write access to submissions
- `admin:users` - Administrative access to user management
- `full:access` - Full system access

## Security Features

1. **API Key Hashing**: All API keys are hashed before storage using SHA-256
2. **Usage Logging**: Every API request is logged with timestamp, endpoint, method, IP address, and user agent
3. **Expiration**: API keys can have expiration dates
4. **Revocation**: API keys can be deactivated or deleted at any time
5. **Scope-based Access**: Fine-grained permissions control what each API key can access

## Developer vs Admin Permissions

| Action | Developer | Admin |
|--------|-----------|-------|
| Create own API keys | ✅ | ✅ |
| Create API keys for others | ❌ | ✅ |
| View own API keys | ✅ | ✅ |
| View all API keys | ❌ | ✅ |
| Update own API keys | ✅ | ✅ |
| Update any API key | ❌ | ✅ |
| Delete own API keys | ✅ | ✅ |
| Delete any API key | ❌ | ✅ |
| View own usage logs | ✅ | ✅ |
| View any usage logs | ❌ | ✅ |

## Usage Examples

### Creating an API Key for a Developer

As an admin, you can create API keys for developers who need to integrate external tools:

```python
import requests

# Admin login
admin_token = login_as_admin()

# Create API key for developer
response = requests.post("http://localhost:8000/auth/api-keys", 
    headers={"Authorization": f"Bearer {admin_token}"},
    json={
        "name": "CI/CD Pipeline Integration",
        "scopes": ["read:projects", "read:tasks", "write:submissions"],
        "user_id": 456,  # Developer's user ID
        "expires_at": "2024-12-31T23:59:59"
    }
)

api_key_data = response.json()
print(f"API Key: {api_key_data['token']}")
```

### Monitoring API Usage

Admins can monitor how API keys are being used:

```python
# Get usage logs for an API key
response = requests.get(f"http://localhost:8000/auth/api-keys/123/usage",
    headers={"Authorization": f"Bearer {admin_token}"}
)

usage_logs = response.json()
for log in usage_logs:
    print(f"{log['timestamp']}: {log['method']} {log['endpoint']} from {log['ip_address']}")
```

## Best Practices

1. **Principle of Least Privilege**: Only grant the minimum scopes necessary
2. **Regular Rotation**: Set expiration dates and rotate API keys regularly
3. **Monitor Usage**: Regularly review API key usage logs
4. **Revoke Unused Keys**: Delete or deactivate API keys that are no longer needed
5. **Secure Distribution**: Share API keys securely and never commit them to version control

## Testing

Use the provided test script to verify admin functionality:

```bash
cd backend
python test_admin_api_keys.py
```

This script demonstrates all admin API key management capabilities.