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

# Authentication

> Authenticate with EngageFabric using JWT tokens or API keys. Learn OAuth2 setup, token refresh, and secure server-to-server authentication patterns.

EngageFabric supports multiple authentication methods depending on your use case:

<CardGroup cols={3}>
  <Card title="API Keys" icon="key">
    For server-to-server communication and backend integrations
  </Card>

  <Card title="JWT Tokens" icon="shield-check">
    For admin console access and user authentication
  </Card>

  <Card title="OAuth2" icon="user-shield">
    Sign in with Google or GitHub for seamless onboarding
  </Card>
</CardGroup>

***

## API Key Authentication

API keys are the recommended way to authenticate your application with EngageFabric. They are project-specific and should be kept secure on your server.

### Getting Your API Key

1. Log in to the [Admin Console](https://admin.engagefabric.com)
2. Navigate to your project
3. Go to **Settings > API Keys**
4. Copy your API key

### Using API Keys

Include your API key in the `X-API-Key` header:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://api.engagefabric.com/api/v1/players" \
    -H "X-API-Key: your-api-key"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.engagefabric.com/api/v1/players', {
    headers: {
      'X-API-Key': 'your-api-key'
    }
  });
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      'https://api.engagefabric.com/api/v1/players',
      headers={'X-API-Key': 'your-api-key'}
  )
  ```
</CodeGroup>

### API Key Types

| Type     | Prefix     | Use Case                |
| -------- | ---------- | ----------------------- |
| **Live** | `ef_live_` | Production environment  |
| **Test** | `ef_test_` | Development and testing |

<Warning>
  **Security Best Practices:**

  * Never expose API keys in client-side code
  * Rotate keys regularly
  * Use environment variables to store keys
  * Use test keys for development
</Warning>

***

## OAuth2 Authentication

EngageFabric supports OAuth2 authentication with Google and GitHub for seamless user onboarding. This is the recommended method for signing up and logging into the admin console.

### Supported Providers

| Provider   | Flow Types          | Best For                             |
| ---------- | ------------------- | ------------------------------------ |
| **Google** | Login, Signup, Link | Business users with Google Workspace |
| **GitHub** | Login, Signup, Link | Developers and technical users       |

### Initiating OAuth Flow

Redirect users to the OAuth endpoint to begin authentication:

<CodeGroup>
  ```bash Google theme={null}
  # Redirect to Google OAuth
  GET https://api.engagefabric.com/api/v1/auth/oauth/google?flow=signup&redirect_uri=https://yourapp.com/callback
  ```

  ```bash GitHub theme={null}
  # Redirect to GitHub OAuth
  GET https://api.engagefabric.com/api/v1/auth/oauth/github?flow=login&redirect_uri=https://yourapp.com/callback
  ```
</CodeGroup>

### Flow Types

| Flow     | Description                             |
| -------- | --------------------------------------- |
| `login`  | Sign in existing user (default)         |
| `signup` | Create new account and tenant           |
| `link`   | Link OAuth provider to existing account |

### OAuth Callback

After successful authentication, users are redirected to your `redirect_uri` with tokens:

```
https://yourapp.com/callback?access_token=eyJ...&refresh_token=eyJ...&token_type=Bearer&expires_in=604800
```

### Getting Available Providers

Check which OAuth providers are enabled:

```bash theme={null}
curl https://api.engagefabric.com/api/v1/auth/oauth/providers
```

**Response:**

```json theme={null}
{
  "providers": [
    { "id": "google", "name": "Google", "enabled": true, "authUrl": "/api/v1/auth/oauth/google" },
    { "id": "github", "name": "GitHub", "enabled": true, "authUrl": "/api/v1/auth/oauth/github" }
  ]
}
```

<Info>
  OAuth is the recommended way to create an EngageFabric account. After signup, users can also set a password for email/password login.
</Info>

***

## JWT Authentication

JWT (JSON Web Tokens) are used for authenticating admin console users and can be used for WebSocket connections.

### Obtaining a JWT Token

```bash theme={null}
curl -X POST "https://api.engagefabric.com/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@example.com",
    "password": "your-password"
  }'
```

**Response:**

```json theme={null}
{
  "accessToken": "eyJhbGciOiJIUzI1NiIs...",
  "user": {
    "id": "user-uuid",
    "email": "admin@example.com",
    "role": "OWNER"
  }
}
```

### Using JWT Tokens

Include the token in the `Authorization` header:

```bash theme={null}
curl -X GET "https://api.engagefabric.com/api/v1/tenants" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
```

### Token Expiration

| Token Type      | Expiration | Use Case              |
| --------------- | ---------- | --------------------- |
| Access Token    | 7 days     | API requests          |
| WebSocket Token | 15 minutes | Real-time connections |

***

## WebSocket Authentication

For real-time features, authenticate WebSocket connections with a short-lived JWT:

```javascript theme={null}
import { io } from 'socket.io-client';

const socket = io('wss://api.engagefabric.com', {
  auth: {
    token: 'your-websocket-jwt'
  }
});

socket.on('connect', () => {
  console.log('Connected to EngageFabric WebSocket');
});
```

<Info>
  WebSocket tokens have a shorter expiration (15 minutes) for security.
  Implement token refresh logic in your application.
</Info>

***

## Role-Based Access Control (RBAC)

EngageFabric implements RBAC for tenant management:

| Role          | Permissions                               |
| ------------- | ----------------------------------------- |
| **Owner**     | Full access, can delete tenant            |
| **Admin**     | Manage projects, users, and settings      |
| **Designer**  | Create and edit rules, quests, adventures |
| **Developer** | Read access, API key management           |
| **Viewer**    | Read-only access to dashboards            |

***

## Rate Limits

API requests are rate-limited based on your project tier:

| Tier           | Rate Limit            |
| -------------- | --------------------- |
| **Free**       | 100 requests/minute   |
| **Starter**    | 500 requests/minute   |
| **Pro**        | 1,000 requests/minute |
| **Enterprise** | Custom limits         |

When rate limited, you'll receive a `429 Too Many Requests` response with headers:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1699900000
```

<Tip>
  Implement exponential backoff when you receive rate limit errors.
</Tip>

***

## Error Responses

Authentication errors return standard error responses:

```json theme={null}
{
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or expired API key",
    "requestId": "req-abc123",
    "timestamp": "2025-01-21T10:00:00Z"
  }
}
```

| Error Code     | HTTP Status | Description                    |
| -------------- | ----------- | ------------------------------ |
| `UNAUTHORIZED` | 401         | Missing or invalid credentials |
| `FORBIDDEN`    | 403         | Insufficient permissions       |
| `RATE_LIMITED` | 429         | Too many requests              |
