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

# Link User Accounts

> Admin-only endpoint to link a secondary user account into a primary account.   - The `userToLinkId` account will be deleted after merging its linked accounts into the primary `userId`.


Admin-only endpoint to link a secondary user account into a primary account. The `userToLinkId` account will be deleted after merging its linked accounts into the primary `userId`.

## Request

### Headers

| Name          | Type   | Required | Description      |
| ------------- | ------ | -------- | ---------------- |
| Authorization | string | Yes      | Bearer token     |
| Content-Type  | string | Yes      | application/json |

### Request Body

```json theme={null}
{
  "payload": {
    "userId": "64b7f1a2e4b0a5d3f9c12345",
    "userToLinkId": "64b7f2b3e4b0a5d3f9c54321"
  }
}
```

### Request Body Schema

| Field                | Type   | Required | Description                             |
| -------------------- | ------ | -------- | --------------------------------------- |
| payload              | object | Yes      | Link accounts payload                   |
| payload.userId       | string | Yes      | Primary user ID (will keep the account) |
| payload.userToLinkId | string | Yes      | Secondary user ID (will be deleted)     |

## Response

### 200 OK - Successfully linked accounts

```json theme={null}
{
  "message": "Accounts linked successfully",
  "data": {
    "updatedPrimaryUser": {
      "_id": "64b7f1a2e4b0a5d3f9c12345",
      "emails": "user@example.com",
      "firstName": "John",
      "lastName": "Doe",
      "role": "user",
      "linkedAccounts": [
        {
          "provider": "google",
          "providerId": "123456789"
        },
        {
          "provider": "microsoft",
          "providerId": "987654321"
        }
      ]
    }
  }
}
```

### 400 Bad Request

```json theme={null}
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request body"
  }
}
```

### 401 Unauthorized

```json theme={null}
{
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Missing or invalid token or insufficient permissions"
  }
}
```

### 404 Not Found

```json theme={null}
{
  "error": {
    "code": "USER_NOT_FOUND",
    "message": "User not found"
  }
}
```

### 500 Internal Server Error

```json theme={null}
{
  "error": {
    "code": "SERVER_ERROR",
    "message": "Internal server error"
  }
}
```

## Example

```bash theme={null}
curl -X POST 'http://localhost:2000/user/link-accounts' \
  -H 'Authorization: Bearer your-jwt-token' \
  -H 'Content-Type: application/json' \
  -d '{
    "payload": {
      "userId": "64b7f1a2e4b0a5d3f9c12345",
      "userToLinkId": "64b7f2b3e4b0a5d3f9c54321"
    }
  }'
```

## Notes

* This is an admin-only endpoint - requires administrative privileges
* Both user IDs must be valid MongoDB ObjectIds
* The secondary account (`userToLinkId`) will be permanently deleted
* All linked accounts from the secondary user are merged into the primary
* This action is irreversible - the secondary account cannot be restored
* Use this to consolidate duplicate user accounts
* The primary user retains their original ID and all merged linked accounts
* Permissions and department assignments from the secondary account are lost


## OpenAPI

````yaml POST /user/link-accounts
openapi: 3.0.3
info:
  title: COMPASS API
  version: 1.0.0
  description: OpenAPI specification for the Compass backend routes.
servers:
  - url: http://localhost:2000
    description: Local development server
security: []
tags:
  - name: Auth
    description: >-
      Authentication and session management endpoints (OAuth and session
      validation)
  - name: Users
    description: Operations for managing user records
  - name: Departments
    description: Operations for managing departments
  - name: Email Meter
    description: APIs to get Email Meter Stats
  - name: HubSpot Tickets
    description: Feedback APIs
  - name: Permissions
    description: Permissions APIs
  - name: Transcription
    description: Transcription APIs
paths:
  /user/link-accounts:
    post:
      tags:
        - Users
      summary: Link two user accounts
      description: >
        Admin-only endpoint to link a secondary user account into a primary
        account.   - The `userToLinkId` account will be deleted after merging
        its linked accounts into the primary `userId`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                payload:
                  $ref: '#/components/schemas/LinkAccountsPayload'
      responses:
        '200':
          description: Successfully linked accounts
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  data:
                    type: object
                    properties:
                      updatedPrimaryUser:
                        $ref: '#/components/schemas/UserSummary'
        '400':
          description: Validation error / bad request
        '401':
          description: Unauthorized (missing/invalid token or insufficient permissions)
        '404':
          description: User not found
        '500':
          description: Server error
      security:
        - bearerAuth: []
components:
  schemas:
    LinkAccountsPayload:
      type: object
      required:
        - userId
        - userToLinkId
      properties:
        userId:
          type: string
          description: The primary user ID to retain
          example: 64ef3c29f9a1c27e1b2c3a4d
        userToLinkId:
          type: string
          description: The secondary user ID to merge into the primary account
          example: 64ef3c29f9a1c27e1b2c3a99
    UserSummary:
      type: object
      properties:
        emails:
          type: array
          items:
            type: string
          example:
            - user@example.com
        personalInformation:
          type: object
          example:
            firstName: John
            lastName: Doe
        role:
          type: string
          example: employee
        department:
          type: object
          example:
            id: 64ef3c29f9a1c27e1b2c3a4d
            role: manager
        reportsTo:
          type: string
          example: 64ef3c29f9a1c27e1b2c3a99
        createdAt:
          type: string
          format: date-time
          example: '2025-09-12T08:30:00Z'
        config:
          type: object
          properties:
            lastActive:
              type: string
              format: date-time
              example: '2025-09-12T09:15:00Z'
        linkedAccounts:
          type: object
          description: Object of linked accounts meta data.
          example:
            google:
              meta:
                email: zain
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

````