> **Client contract note:** Apply [`shared/response-envelope.md`](../shared/response-envelope.md) to JSON responses after the response-contract release. Legacy wrapper examples below may reflect the prior API; the documented endpoint-specific payload fields are still useful. Not staging-verified.

# Impersonation — Outlet API handoff (dashboard)

> **Verification boundary:** The detailed contract below was derived from repository source, not from live HTTP captures. Fields explicitly marked unverified remain open. The earlier route inventory is retained below for cross-checking; where it says “not verified”, the more recent source-reviewed contract takes precedence.

## Controller-reviewed contracts


**Base URL:** `/api/v1` · **Source:** GitLab `alalmiyalhura/outlet`, `main` · **Consumer:** Dashboard administration. **Verification:** Static review of routes, controller, form request, service and configuration; not live API-tested. All JSON examples are illustrative, not captured traffic.

## Shared contract and security

- All three operations require `Authorization: Bearer <Sanctum token>` and `Accept: application/json`.
- `GET /impersonation/sessions` and `POST /impersonation/{target}/start` require ability **`users.impersonate`**. `POST /impersonation/stop` requires authentication but **not** that ability, allowing an impersonated user to end their own session.
- A target account with `users.impersonate` is protected from impersonation. The caller cannot impersonate themselves or start another impersonation from an impersonation token. Missing and protected targets are deliberately concealed as not-found.
- A start replaces/revokes any previous active impersonation session for the administrator. Issued token has a short expiry; defaults: **30 minutes**, maximum **120 minutes** (environment configurable).
- Some operations are blocked while impersonating, including `PATCH me`, `POST auth/logout-all`, and starting another impersonation. The configuration also blocks `DELETE users/*` and `POST auth/password/*`.
- Response envelope for success is `{"data": ...}` except `204 No Content`. Standard errors depend on shared Core exception handling. Common categories: 401 unauthenticated, 403 missing permission, 404 concealed target/session, 422 invalid input. Exact error codes for all failure branches are **not yet verified**.

## 1. POST `/api/v1/impersonation/{target}/start`

**Purpose:** A permitted support/admin operator temporarily assumes a *non-protected* user's identity for troubleshooting. **Auth:** Sanctum + `users.impersonate`. **Rate limit:** 10 requests/minute. **Success:** `201 Created`.

### Path parameters

| Field | Type | Required | Validation | Meaning |
|---|---|---|---|---|
| `target` | integer | Yes | numeric route segment | Target user ID; must exist and not be protected. |

### Request JSON

| Field | Type | Required | Validation | Meaning |
|---|---|---|---|---|
| `reason` | string | Yes | min 10, max 500 characters | Auditable explanation, e.g. support ticket. Trimmed before persistence. |
| `minutes` | integer | No | min 1, max configured `impersonation.max_minutes` (120 by default) | Requested session lifetime; absent uses configured default (30). |

```http
POST /api/v1/impersonation/204/start HTTP/1.1
Authorization: Bearer <ADMIN_TOKEN>
Content-Type: application/json
Accept: application/json

{"reason":"Investigate support ticket SUP-1024","minutes":20}
```

### Example response (`201`)

```json
{
  "data": {
    "token": "<NEW_SHORT_LIVED_SANCTUM_TOKEN>",
    "session_id": 51,
    "expires_at": "2026-11-22T14:20:00+00:00",
    "user": {"id": 204, "name": "Example User", "email": "user@example.com"}
  }
}
```

| Response field | Type | Meaning |
|---|---|---|
| `data.token` | string | New bearer token **for the target user**; treat as secret. |
| `data.session_id` | integer | Audit/session identifier. |
| `data.expires_at` | string (ISO-8601 datetime) | Session expiry. |
| `data.user` | object | Target account returned by target-user provider. Service contract declares `id` integer, `name` string, `email` string. |
| `data.user.id` | integer | Target user ID. |
| `data.user.name` | string | Target display name. |
| `data.user.email` | string | Target email (verify nullability with provider if needed). |

**Side effects:** Ends and revokes older active impersonation tokens for the same administrator, records new session, emits `impersonation.started` webhook, and optionally notifies target (enabled by default). **Errors:** 401/403, 404 for nonexistent/protected target, 422 for invalid reason or minutes, rate-limit 429; domain may reject self-impersonation or nesting. **Dashboard handling:** Preserve original admin token securely; use issued token only for scoped support session, then call stop; never log the issued token.

## 2. POST `/api/v1/impersonation/stop`

**Purpose:** End the currently active impersonation session identified by the bearer token. **Auth:** Sanctum impersonation token; no `users.impersonate` ability required. **Body:** none. **Success:** `204 No Content`, no JSON body.

```http
POST /api/v1/impersonation/stop HTTP/1.1
Authorization: Bearer <IMPERSONATION_TOKEN>
Accept: application/json
```

**Response:** HTTP `204` with empty body. **Side effects:** Marks the session `stopped`, revokes the impersonation token and emits `impersonation.ended`. **Errors:** 401 if unauthenticated; not-found when the bearer token is not an active impersonation token. **Dashboard handling:** Switch back to preserved original admin token after successful stop. Do not send the original admin token to stop; the endpoint resolves the session using the *current token ID*.

## 3. GET `/api/v1/impersonation/sessions`

**Purpose:** Return recent impersonation sessions for authorized admins. **Auth:** Sanctum + `users.impersonate`. **Query:** none supported by controller. **Body:** none. **Success:** `200 OK`.

```http
GET /api/v1/impersonation/sessions HTTP/1.1
Authorization: Bearer <ADMIN_TOKEN>
Accept: application/json
```

### Response contract

```json
{
  "data": []
}
```

| Response field | Type | Meaning |
|---|---|---|
| `data` | array<object> | Up to 50 recent session records, as returned by `ImpersonationStore::recent(50)`. |

**Important verification gap:** The controller/service confirms `data` is a list with default limit 50, but the exact properties of each session row require inspection of the concrete store implementation. No invented session-row schema is presented as verified. **Errors:** 401/403. **Dashboard handling:** Read-only admin session history; no pagination parameters in the controller.

## Screen-to-endpoint mapping

| Dashboard screen/action | API | Notes |
|---|---|---|
| User details → “View as user” | `POST /impersonation/{target}/start` | Requires documented reason and permission. |
| Impersonation banner → “End session” | `POST /impersonation/stop` | Send issued impersonation bearer token. |
| Admin security/support → session log | `GET /impersonation/sessions` | Admin-only recent sessions. |
| Flutter app | No direct impersonation workflow assumed | Admin-support capability; don't expose to ordinary mobile users. |

## Sources reviewed

- `modules/Impersonation/Routes/api.php`
- `modules/Impersonation/Interfaces/Http/Controllers/ImpersonationController.php`
- `modules/Impersonation/Interfaces/Http/Requests/StartImpersonationRequest.php`
- `modules/Impersonation/Application/ImpersonationService.php`
- `modules/Impersonation/Config/impersonation.php`

**Remaining checks:** Concrete `ImpersonationStore::recent` payload, exact domain error-to-HTTP mapping, integration tests, and dashboard implementation. Do not mark live integration verified from this document alone.


---

## Verified domain error codes and operational behavior (source audit)

Sources: `Application/ImpersonationService.php`, `Interfaces/Http/Requests/StartImpersonationRequest.php`, `Domain/Exception/ImpersonationDenied.php`, `Domain/Exception/ImpersonationNotFound.php` on GitLab `main`. These are source-derived, **not** live response captures.

| Condition | HTTP | Domain code | Client action |
|---|---:|---|---|
| Start on own account | 403 | `impersonation_self` | Reject self-target selection |
| Start from an existing impersonation | 403 | `impersonation_nested` | Stop current session first |
| Protected target | 403 | `impersonation_protected_user` | Do not retry; server policy |
| Action blocked during impersonation | 403 | `impersonation_forbidden_action` | Disable restricted action |
| Target missing or session/token not active | 404 (ResourceNotFound) | `impersonation_not_found` | Clear stale session state |
| `reason` missing or shorter than 10 / longer than 500 characters | 422 | validation error | Correct request |
| `minutes` outside `1..config('impersonation.max_minutes')` | 422 | validation error | Correct duration |

The `start` service revokes prior active sessions belonging to the administrator, issues a **new target-user token**, persists a session, and returns `token`, `session_id`, `expires_at`, and `user` (`id`, `name`, `email`). The service also publishes `impersonation.started` and optionally notifies the target. Never log or display the returned token beyond the authenticated session setup.

`POST /impersonation/stop` requires the **impersonation token** and responds `204` with **no JSON body**; the service ends the session, revokes its token, and publishes `impersonation.ended`. The `GET /impersonation/sessions` service returns up to **50 recent sessions** by default; it is not a paginated endpoint in the controller.
