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

# Auth Sessions API Reference

## Overview

The Auth Sessions API provides comprehensive management tools for user authentication sessions on your Publica.la platform. It enables you to monitor active sessions, manage user access, and maintain security by terminating sessions when needed.

This API is particularly useful for administrators who need to monitor user activity, implement security policies, or manage user access across multiple devices and browsers.

:::info
Make sure you generated the **api_token** on your store. More info in the [API Authentication guide](overview.md)
:::

## Endpoint Reference

| Endpoint                                                         | Method | Description                                          |
| ---------------------------------------------------------------- | ------ | ---------------------------------------------------- |
| [/integration-api/v1/auth-sessions](#list)                       | GET    | List authentication sessions with optional filtering |
| [/integration-api/v1/auth-sessions/(id)](#delete)                | DELETE | Delete a specific authentication session             |
| [/integration-api/v1/auth-sessions/users/(user_id)](#delete-all) | DELETE | Delete all authentication sessions for a user        |

## List Auth Sessions {#list}

Retrieve a paginated list of authentication sessions with optional filtering by user.

**Endpoint:** `GET /integration-api/v1/auth-sessions`

### Query Parameters

| Parameter   | Type    | Description                                      | Example                              |
| ----------- | ------- | ------------------------------------------------ | ------------------------------------ |
| user_id     | integer | Filter sessions by specific user ID              | `?user_id=123`                       |
| external_id | string  | Filter sessions by specific user external ID     | `?external_id=user-123`              |
| per_page    | integer | Number of results per page (1-200, default: 100) | `?per_page=50`                       |
| cursor      | string  | Pagination cursor for next page                  | `?cursor=eyJsYXN0X2FjdGl2aXR5Ijo...` |

### Response Fields

| Field                  | Description                         | Type        |
| ---------------------- | ----------------------------------- | ----------- |
| CODE                   | Response status code                | string      |
| data                   | Array of auth session objects       | array       |
| pagination.per_page    | Number of items per page            | integer     |
| pagination.next_cursor | Cursor for next page (if available) | string/null |
| pagination.has_more    | Whether more pages are available    | boolean     |

#### Auth Session Object Fields

| Field              | Description                                             | Type        |
| ------------------ | ------------------------------------------------------- | ----------- |
| id                 | Unique session identifier                               | string      |
| user_id            | ID of the user who owns this session                    | integer     |
| user_email         | Email of the user who owns this session                 | string      |
| user_external_id   | External ID of the user who owns this session           | string/null |
| ip_address         | IP address from which session was created               | string      |
| session_data       | Session information (web browser or mobile app details) | object      |
| last_activity      | Last activity timestamp in ISO format                   | string      |
| last_activity_diff | Human-readable time since last activity                 | string      |
| session_expires_at | Session expiration timestamp in ISO format              | string      |

#### Example Request

```bash
GET /integration-api/v1/auth-sessions?user_id=123&per_page=25
```

Or filter by external ID:

```bash
GET /integration-api/v1/auth-sessions?external_id=user-123&per_page=25
```

#### Example Response

```json
{
  "CODE": "success",
  "data": [
    {
      "id": "abc123def456ghi789",
      "user_id": 123,
      "user_email": "user@example.com",
      "user_external_id": "user-id-in-your-platform",
      "ip_address": "192.168.1.100",
      "session_data": {
        "browser": "Chrome",
        "device": "Desktop",
        "os": "macOS",
        "type": "web",
        "raw": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
      },
      "last_activity": "2023-12-29T10:00:00",
      "last_activity_diff": "10 minutes ago",
      "session_expires_at": "2023-12-29T12:00:00"
    },
    {
      "id": "def789ghi123abc456",
      "user_id": 123,
      "user_email": "user@example.com",
      "user_external_id": "user-id-in-your-platform",
      "ip_address": "192.168.1.101",
      "session_data": {
        "app_name": "Publica Reader",
        "app_version": "2.1.0",
        "os": "iOS",
        "os_version": "17.2",
        "type": "mobile",
        "raw": "PublicaReader/2.1.0 iOS/17.2"
      },
      "last_activity": "2023-12-29T09:45:00",
      "last_activity_diff": "25 minutes ago",
      "session_expires_at": "2024-12-29T09:45:00"
    }
  ],
  "pagination": {
    "per_page": 25,
    "next_cursor": "eyJsYXN0X2FjdGl2aXR5IjoxNzAzODc1MjAwLCJpZCI6ImFiYzEyM2RlZjQ1NmdoaTc4OSJ9",
    "has_more": true
  }
}
```

### Response Codes

| Code  | Description                           |
| :---- | :------------------------------------ |
| `200` | Success                               |
| `422` | Validation error (invalid parameters) |
| `401` | Unauthorized (invalid API token)      |

## Session Data Structure

The API returns session information through the `session_data` field, which provides detailed information about each authentication session.

### Web Sessions

Web sessions are created when users log in through a browser and contain browser-specific information:

```json
{
  "session_data": {
    "browser": "Chrome", // Browser name (Chrome, Firefox, Safari, etc.)
    "device": "Desktop", // Device type (Desktop, Mobile, Tablet)
    "os": "macOS", // Operating system
    "type": "web", // Always "web" for browser sessions
    "raw": "Mozilla/5.0..." // Original user agent string
  }
}
```

### Mobile Sessions

Mobile sessions are created when users authenticate through mobile applications (Publica.la Reader or any custom tenant apps) and contain app-specific information:

```json
{
  "session_data": {
    "app_name": "Publica Reader", // Application name
    "app_version": "2.1.0", // App version
    "os": "iOS", // Mobile operating system
    "os_version": "17.2", // OS version
    "type": "mobile", // Always "mobile" for app sessions
    "raw": "PublicaReader/2.1.0..." // Original user agent string
  }
}
```

### Session Type Detection

You can easily distinguish between web and mobile sessions by checking the `session_data.type` field:

- `"type": "web"` indicates a browser-based session
- `"type": "mobile"` indicates a mobile app session

This allows you to implement different handling logic for each session type in your integration.

## Delete Specific Session {#delete}

Delete a specific authentication session by its ID.

**Endpoint:** `DELETE /integration-api/v1/auth-sessions/(id)`

### Path Parameters

| Parameter | Type   | Description              | Required |
| --------- | ------ | ------------------------ | -------- |
| id        | string | The session ID to delete | Yes      |

#### Example Request

```bash
DELETE /integration-api/v1/auth-sessions/abc123def456ghi789
```

#### Example Response

```json
{
  "CODE": "success",
  "message": "Session deleted successfully"
}
```

### Response Codes

| Code  | Description                      |
| :---- | :------------------------------- |
| `200` | Session deleted successfully     |
| `404` | Session not found                |
| `401` | Unauthorized (invalid API token) |

## Delete All User Sessions {#delete-all}

Delete all authentication sessions for a specific user.

**Endpoint:** `DELETE /integration-api/v1/auth-sessions/users/(user_id)`

### Path Parameters

| Parameter | Type    | Description                                  | Required |
| --------- | ------- | -------------------------------------------- | -------- |
| user_id   | integer | The user ID whose sessions should be deleted | Yes      |

#### Example Request

```bash
DELETE /integration-api/v1/auth-sessions/users/123
```

#### Example Response

```json
{
  "CODE": "success",
  "message": "Deleted 3 sessions successfully",
  "data": {
    "deleted_count": 3
  }
}
```

### Response Codes

| Code  | Description                      |
| :---- | :------------------------------- |
| `200` | Sessions deleted successfully    |
| `404` | User not found                   |
| `401` | Unauthorized (invalid API token) |

## Use Cases

### Security Management

Monitor and manage user sessions to maintain platform security:

- **Identify suspicious activity**: Review sessions from unusual IP addresses or locations
- **Enforce device limits**: Monitor concurrent sessions per user
- **Immediate access revocation**: Quickly terminate compromised sessions

### Administrative Tasks

- **User support**: Help users manage their active sessions
- **Account cleanup**: Remove old or inactive sessions
- **Access control**: Ensure users only have authorized active sessions

### Integration Examples

**Session Analysis:**

```javascript
// Analyze user session patterns
const userId = 123;

const response = await fetch(
  `/integration-api/v1/auth-sessions?user_id=${userId}`,
  {
headers: {
  'X-User-Token': 'your-api-token',
},
  }
);

const result = await response.json();
const sessions = result.data;

// Categorize sessions by type
const webSessions = sessions.filter((s) => s.session_data.type === 'web');
const mobileSessions = sessions.filter((s) => s.session_data.type === 'mobile');

console.log(
  `User has ${webSessions.length} web sessions and ${mobileSessions.length} mobile sessions`
);

// Get details about mobile apps being used
const mobileApps = mobileSessions.map((s) => ({
  app: s.session_data.app_name,
  version: s.session_data.app_version,
  platform: `${s.session_data.os} ${s.session_data.os_version}`,
  lastActive: s.last_activity_diff,
}));

console.log('Mobile app usage:', mobileApps);

// Get browser information
const browsers = webSessions.map((s) => ({
  browser: s.session_data.browser,
  device: s.session_data.device,
  os: s.session_data.os,
  lastActive: s.last_activity_diff,
}));

console.log('Browser usage:', browsers);
```

---

**Session Limit Management:**

```javascript
// Manage session limits for a user
const userId = 123;
const maxSessions = 3;

// Get all sessions for the user
const response = await fetch(
  `/integration-api/v1/auth-sessions?user_id=${userId}`,
  {
headers: {
  'X-User-Token': 'your-api-token',
},
  }
);

const result = await response.json();
const sessions = result.data;

console.log(`User has ${sessions.length} active sessions`);

// If user exceeds session limit, remove oldest sessions
if (sessions.length > maxSessions) {
  // Sort by last_activity (oldest first)
  const sortedSessions = sessions.sort(
(a, b) => new Date(a.last_activity) - new Date(b.last_activity)
  );

  // Calculate how many sessions to remove
  const sessionsToRemove = sessions.length - maxSessions;
  const oldestSessions = sortedSessions.slice(0, sessionsToRemove);

  // Delete oldest sessions
  for (const session of oldestSessions) {
await fetch(`/integration-api/v1/auth-sessions/${session.id}`, {
  method: 'DELETE',
  headers: {
    'X-User-Token': 'your-api-token',
  },
});
console.log(
  `Deleted session: ${session.id} (last active: ${session.last_activity_diff})`
);
  }
}
```

---

**User Session Cleanup:**

```javascript
// Remove all sessions for a specific user
const userId = 123;

const response = await fetch(
  `/integration-api/v1/auth-sessions/users/${userId}`,
  {
method: 'DELETE',
headers: {
  'X-User-Token': 'your-api-token',
},
  }
);

const result = await response.json();
console.log(`Deleted ${result.data.deleted_count} sessions for user ${userId}`);
```

:::warning
Deleting sessions will immediately log out users from their current devices. Use this functionality carefully to avoid disrupting legitimate user activity.
:::
