# Frontend Auth Guide

This file explains how frontend should use authentication APIs in this project.

## 1. Important Idea

This backend uses **cookie-based session auth**.

- Login response does **not** return a token in JSON body.
- Backend sets a cookie (default name: `dsp_session`) in `Set-Cookie` header.
- Browser stores it automatically.
- Browser sends it automatically on next protected API calls.

So frontend should not store any token from signin response body.

## 2. What to do after login

Call signin API once with email/password.

### Signin API

- Endpoint: `POST /auth/signin`
- Body:

```json
{
  "email": "user@example.com",
  "password": "YourPassword123!"
}
```

### Expected response body

```json
{
  "success": true,
  "message": "Signin successful",
  "data": {
    "id": "62",
    "companyName": "test",
    "firstName": "Test",
    "lastName": "User",
    "email": "user@example.com",
    "statusId": 4,
    "currency": "USD",
    "createdAt": "...",
    "updatedAt": "..."
  }
}
```

The session id is inside cookie, not inside this JSON.

## 3. What to send in protected APIs

For protected APIs (campaigns, line-items, dashboard, etc.), frontend must send requests with cookies enabled.

### fetch example

```ts
await fetch("http://localhost:3000/campaigns", {
  method: "GET",
  credentials: "include",
});
```

### axios example

```ts
import axios from "axios";

export const api = axios.create({
  baseURL: "http://localhost:3000",
  withCredentials: true,
});

// usage
const response = await api.get("/campaigns");
```

Set this once in shared API client. Do not repeat manually everywhere.

## 4. How frontend knows user is logged in

Use `GET /auth/me`.

- If session is valid -> `200` + user data
- If not logged in -> `401`

### Example

```ts
const response = await api.get("/auth/me");
```

## 5. Logout flow

### Act as an advertiser

- Start with `POST /admin/advertisers/:id/act-as` from admin mode. The login cookie
  stays the same; the selected advertiser becomes the effective account with
  advertiser permissions. No user in that account is needed.
- Refetch `GET /auth/me` and clear data cached for the previous account after
  starting or stopping. For admins, `/auth/me` returns the real admin's account
  and personal details, with `impersonation: null` in admin mode. During act-as,
  `impersonation.advertiser` contains the target account, its advertiser role,
  billing, verification, status and delivery information. Admin responses omit
  those advertiser-only fields at the top level. Advertiser `/auth/me` responses
  and other auth endpoints retain their existing formats.
- Use `impersonation.advertiser` as the effective account for UI scoping,
  permissions and verification when present; never use the top-level admin role
  to grant admin controls during act-as. The API independently enforces this.
- Pause the admin advertiser-detail query before starting the switch so clearing
  the old cache cannot refetch `/admin/advertisers/:id` in advertiser mode.
- Password and personal-name edits are not available during act-as; company
  and billing profile edits still apply to the effective advertiser.
- If an API request returns `ACT_AS_ENDED`, call
  `POST /admin/advertisers/act-as/stop` and refetch `/auth/me`. The stop call also
  works after the target is disabled or removed, as long as the original login
  is still valid. No failing advertiser request is automatically retried in
  admin mode.

### Logout current session

- Endpoint: `POST /auth/signout`
- Server clears session cookie and removes current session.

```ts
await api.post("/auth/signout");
```

After logout, protected APIs return `401` until user logs in again.

## 6. Common mistakes

### Password recovery eligibility

- `POST /auth/forgot-password` sends a reset email only when both the user and
  advertiser are `ACTIVE`.
- Missing emails, `INVITED` or `DEACTIVATED` users, other non-active user statuses,
  and non-active advertisers receive the same HTTP 200 response, without creating
  a reset token or sending a recovery email.
- Display conditional confirmation: "If this email belongs to an eligible account,
  you'll receive password-reset instructions." Do not claim an email was sent.
- `POST /auth/reset-password` rechecks token validity and account eligibility at
  submission time. An unused, unexpired token does not override account status.
  Rejected resets do not change the password or activate the user.
- Invited users must accept an invitation to set their password and become active.
  If needed, their administrator can resend the invitation. Deactivated users
  must be reactivated by their administrator before requesting password recovery.

1. Expecting token in signin JSON:

- Not used in this project.

2. Not enabling credentials:

- If `credentials: include` / `withCredentials: true` is missing, cookie may not be sent.

3. Different domain/port mismatch:

- Cookies are domain scoped. Use correct API base URL.

4. Trying to read `dsp_session` in JS:

- Cookie is HTTP-only for security. JS cannot read it.

## 7. Quick checklist for FE dev

1. Create shared API client with `withCredentials: true`.
2. Call `POST /auth/signin` once.
3. Call `GET /auth/me` to confirm login state.
4. Call protected APIs normally through shared client.
5. For logout, call `POST /auth/signout`.

## 8. Optional curl testing

Signin and save cookie:

```bash
curl.exe -i -X POST "http://localhost:3000/auth/signin" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"user@example.com\",\"password\":\"YourPassword123!\"}" \
  -c cookies.txt
```

Use cookie for protected API:

```bash
curl.exe -i "http://localhost:3000/auth/me" -b cookies.txt
```

Logout:

```bash
curl.exe -i -X POST "http://localhost:3000/auth/signout" -b cookies.txt -c cookies.txt
```
