> ## Documentation Index
> Fetch the complete documentation index at: https://docs-ts.playservices.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication & Security

> API key management, role-based permissions, and security best practices for casino integration

# Authentication & Security

The Tournament Platform uses operator API keys with role-based permissions to provide secure, multi-tenant access to tournament functionality.

## API Key Authentication

All Casino Integration APIs require authentication via operator API keys passed in the Authorization header:

```http theme={null}
GET /api/tournaments
Authorization: Bearer {your-operator-api-key}
Content-Type: application/json
```

### API Key Format

Tournament Platform uses compound API keys with the following format:

* **Format**: `pk_xxx:sk_yyy` where `pk_` is the public key prefix and `sk_` is the secret key prefix
* **Example**: `pk_1234567890abcdef:sk_9876543210fedcba...`
* **Usage**: The full compound key is used in the Authorization header
* **Security**: Keys use SHA256 hashing for authentication validation

## Role-Based Permissions

<Info>
  API keys are assigned to operator roles that define specific permissions. This enables fine-grained access control for different use cases.
</Info>

### Available Permissions

| Permission           | Description                         | Example Use Case                                  |
| -------------------- | ----------------------------------- | ------------------------------------------------- |
| `tournaments.read`   | View tournaments and status         | Displaying tournament lists, checking status      |
| `tournaments.write`  | Create and update tournaments       | Creating scheduled tournaments, updating settings |
| `tournaments.delete` | Cancel tournaments                  | Emergency tournament cancellation                 |
| `players.read`       | View player data and registrations  | Displaying participant lists, player stats        |
| `players.write`      | Register and manage players         | Player registration, rebuy processing             |
| `results.read`       | Access results and leaderboard data | Showing leaderboards, final results               |

### Common Role Configurations

<Tabs>
  <Tab title="Full Access">
    **All Permissions** - For primary integration systems:

    ```json theme={null}
    {
      "permissions": [
        "tournaments.read",
        "tournaments.write", 
        "tournaments.delete",
        "players.read",
        "players.write",
        "results.read"
      ]
    }
    ```
  </Tab>

  <Tab title="Tournament Manager">
    **Tournament Operations** - For tournament management systems:

    ```json theme={null}
    {
      "permissions": [
        "tournaments.read",
        "tournaments.write",
        "players.read",
        "players.write",
        "results.read"
      ]
    }
    ```
  </Tab>

  <Tab title="Read Only">
    **Monitoring & Reporting** - For analytics and reporting systems:

    ```json theme={null}
    {
      "permissions": [
        "tournaments.read",
        "players.read", 
        "results.read"
      ]
    }
    ```
  </Tab>

  <Tab title="Player Registration">
    **Registration System** - For player management systems:

    ```json theme={null}
    {
      "permissions": [
        "tournaments.read",
        "players.read",
        "players.write"
      ]
    }
    ```
  </Tab>
</Tabs>

## API Key Management

### Creating API Keys

<Steps>
  <Step title="Access Operator Dashboard">
    Log into your Tournament Platform operator dashboard
  </Step>

  <Step title="Navigate to API Keys">
    Go to Settings → API Keys section
  </Step>

  <Step title="Create New Key">
    Click "Create API Key" and provide:

    * **Name**: Descriptive name for the key
    * **Role**: Select appropriate role with required permissions
    * **Expiration**: Optional expiration date for security
  </Step>

  <Step title="Copy Key Secret">
    **Important**: Copy the key secret immediately - it won't be shown again
  </Step>
</Steps>

### Key Security Best Practices

<Warning>
  **Never expose API keys in client-side code, public repositories, or logs**. Keys should only be used in secure server-to-server communication.
</Warning>

#### Storage & Environment

* Store keys in environment variables or secure credential management systems
* Use different keys for development, staging, and production environments
* Rotate keys regularly (recommended: every 90 days)
* Set expiration dates on keys when possible

#### Access Control

* Use least-privilege principle - grant only necessary permissions
* Create separate keys for different systems or purposes
* Monitor key usage and disable unused keys
* Implement IP whitelist restrictions when possible

### Example Environment Configuration

```bash theme={null}
# .env file
TOURNAMENT_API_KEY=pk_1234567890abcdef:sk_9876543210fedcba...
TOURNAMENT_API_BASE_URL=https://ts.playservices.tech/api
```

```javascript theme={null}
// Node.js example
const apiKey = process.env.TOURNAMENT_API_KEY;
const baseUrl = process.env.TOURNAMENT_API_BASE_URL;

const headers = {
  'Authorization': `Bearer ${apiKey}`,
  'Content-Type': 'application/json'
};
```

## Multi-Tenant Security

### Operator Isolation

The Tournament Platform provides complete tenant isolation:

* **Data Scoping**: All API responses automatically filtered by operator ID
* **Resource Access**: No cross-operator access to tournaments or players
* **Configuration Isolation**: Independent webhook URLs, settings, and preferences
* **Audit Trails**: Separate audit logs per operator

### Request Validation

Every API request undergoes:

1. **API Key Validation**: Verify key exists and is active
2. **Permission Check**: Ensure key has required permissions for operation
3. **Operator Scoping**: Filter all data to operator's resources only
4. **Rate Limiting**: Apply per-operator rate limits
5. **Request Logging**: Log all API access for audit purposes

## Rate Limiting

### Standard Limits

| Operation Type        | Limit         | Window     |
| --------------------- | ------------- | ---------- |
| Tournament Operations | 100 requests  | per minute |
| Tournament Creation   | 10 requests   | per minute |
| Player Registration   | 200 requests  | per minute |
| Results/Leaderboards  | 500 requests  | per minute |
| General API Calls     | 1000 requests | per minute |

### Rate Limit Headers

API responses include rate limit information:

```http theme={null}
HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1642089600
```

### Handling Rate Limits

```javascript theme={null}
const makeApiRequest = async (url, options) => {
  const response = await fetch(url, options);
  
  if (response.status === 429) {
    const resetTime = response.headers.get('X-RateLimit-Reset');
    const delay = (resetTime * 1000) - Date.now();
    
    console.log(`Rate limited. Retrying in ${delay}ms`);
    await new Promise(resolve => setTimeout(resolve, delay));
    
    return makeApiRequest(url, options);
  }
  
  return response;
};
```

## Error Handling

<Info>
  All API endpoints return consistent JSON error responses. The platform no longer returns HTML error pages for validation failures.
</Info>

### Authentication Errors

#### 401 Unauthorized

```json theme={null}
{
  "error": "unauthorized",
  "message": "Invalid API key",
  "code": "INVALID_API_KEY"
}
```

**Common causes:**

* Invalid or expired API key
* Malformed Authorization header
* Key not found in system

#### 403 Forbidden

```json theme={null}
{
  "error": "forbidden", 
  "message": "Insufficient permissions for this operation",
  "code": "INSUFFICIENT_PERMISSIONS",
  "required_permission": "tournaments.write"
}
```

**Common causes:**

* API key lacks required permission
* Attempting to access another operator's resources
* Operation not allowed for key's role

#### 422 Validation Error

```json theme={null}
{
  "message": "The given data was invalid.",
  "errors": {
    "name": ["The name field is required."],
    "max_players": ["The max players must be at least 1."],
    "scheduled_start": ["The scheduled start field must be a valid date."]
  }
}
```

**Common causes:**

* Missing required fields
* Invalid data formats
* Business rule violations

### Security Headers

All API responses include security headers:

```http theme={null}
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
```

## Testing Authentication

### Verify API Key

```bash theme={null}
curl -X GET "https://ts.playservices.tech/api/tournaments" \
  -H "Authorization: Bearer pk_1234567890abcdef:sk_9876543210fedcba..." \
  -H "Content-Type: application/json"
```

**Expected Response (200 OK):**

```json theme={null}
{
  "data": [
    {
      "id": "12345",
      "name": "Daily Championship",
      "status": "scheduled",
      "scheduled_start": "2024-01-15T20:00:00Z"
    }
  ],
  "current_page": 1,
  "per_page": 15,
  "total": 1
}
```

### Check Permissions

```bash theme={null}
curl -X GET "https://ts.playservices.tech/api/auth/permissions" \
  -H "Authorization: Bearer pk_1234567890abcdef:sk_9876543210fedcba..."
```

**Response:**

```json theme={null}
{
  "operator_id": "op_1234567890abcdef",
  "api_key_id": "key_1234567890abcdef", 
  "permissions": [
    "tournaments.read",
    "tournaments.write",
    "players.read",
    "players.write",
    "results.read"
  ],
  "expires_at": "2024-12-31T23:59:59Z"
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Tournament Management" icon="trophy" href="/casino-integration/tournament-management">
    Start creating and managing tournaments with your authenticated API access.
  </Card>

  <Card title="Player Management" icon="users" href="/casino-integration/player-management">
    Learn how to register and manage players in your tournaments.
  </Card>
</CardGroup>
