# Backend Implementation Guide — `pcqaapi` (pastorchrisonline.org)

This documents the backend work required to support two App Store Review fixes made in the iOS app:

1. **Guest access to informational content** — enforce that content requests come from the mobile app, and rate-limit abuse.
2. **Account deletion** — a new endpoint so users can permanently delete their account from within the app.

The backend is a PHP API at `https://pastorchrisonline.org/pcqaapi/api.php` dispatched by a `ty=` query parameter (e.g. `ty=content/posts`, `ty=auth/login`, `ty=user/delete`).

---

## 1. Request verification for guest/content endpoints

### Problem
Guests (not logged in) now access `content/posts`, `content/categories`, `content/banners`, `content/post`, `content/search`. The app sends `Authorization: Bearer false` for guests, which proves nothing. We need to verify the request actually comes from our mobile app and deter bulk scraping.

### What the app now sends on EVERY request
Both iOS and Android send these headers on all requests:

| Header | Value | Purpose |
|---|---|---|
| `X-App-Key` | Shared secret (same on iOS + Android) | Proves "from our app" (deterrence) |
| `X-Device-Id` | Per-install persistent anonymous UUID | Identifies an install; use for rate limiting / abuse detection |

Authenticated requests additionally send the existing user token (e.g. `Authorization: Bearer <token>`), which remains the authority for user-specific actions.

### Server-side rule (recommended)
For **all** endpoints, at the very top of the request handler:

1. Read `X-App-Key` from the request headers.
2. Compare to the configured expected key (keep it server-side in a config/env var, **not** hardcoded inline where it's easy to miss).
   - If missing or not equal → return `HTTP 401` with `{ "success": false, "message": "Unauthorized" }`.
3. Read `X-Device-Id`; if missing → `HTTP 401`.
4. Optionally verify format (a UUID regex) — if it looks like a crafted value, you may still allow but enforce stricter rate limits.

### Rate limiting (per `X-Device-Id`)
To deter bulk scraping, rate-limit by `X-Device-Id` per endpoint (e.g. token bucket / sliding window in Redis, or a DB table):

- `content/posts`, `content/categories`, `content/banners`, `content/post`: e.g. **60 requests / minute** per device id.
- `content/search`: stricter, e.g. **20 requests / minute** per device id.
- When exceeded → `HTTP 429` with `{ "success": false, "message": "Too many requests" }` and a `Retry-After` header.

Store the device id in an indexable column. Optionally keep a separate table `device_requests(device_id, endpoint, requested_at)` for analytics/abuse review, and support blocking specific device ids.

### Pseudocode (PHP)

```php
function get_header($name, $default = null) {
    // Use getallheaders() or $_SERVER['HTTP_X_APP_KEY'] etc.
    $headers = getallheaders();
    return isset($headers[$name]) ? $headers[$name] : $default;
}

function require_app_key() {
    $expected = getenv('PCQA_APP_KEY'); // shared secret, server-side only
    $key = get_header('X-App-Key');
    if ($key !== $expected) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        exit;
    }
    $deviceId = get_header('X-Device-Id');
    if (!$deviceId) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Missing device id']);
        exit;
    }
    return $deviceId;
}

// Call at the start of every api.php request:
$deviceId = require_app_key();
```

### Important notes
- The app-key value must match `appApiKey` in iOS `lib/config.js` and the Android `AppConfig.APP_API_KEY`. Since it's embedded in the app it's extractable; treat it as a shared secret but understand it is not true attestation. Rotate it if it leaks.
- **Do not** break the Android private-store client: the same headers are used, so no platform branching is needed.
- Keep guest content reads working without a user token. The old `Authorization: Bearer false` can be ignored for guest endpoints.
- Log failures for monitoring, but be mindful of PII — device ids are anonymous.

---

## 2. Account deletion endpoint

### Requirement
Apps that support account creation must offer in-app account deletion (Guideline 5.1.1(v)). The iOS app added a "Delete Account" flow that calls this endpoint, then wipes local data and restarts.

### Endpoint contract
`POST https://pastorchrisonline.org/pcqaapi/api.php?ty=user/delete`

**Request body (JSON):**
```json
{
  "id": 12345,
  "email": "user@example.com"
}
```

**Headers:** the normal `X-App-Key` / `X-Device-Id`, plus `Authorization: Bearer <userToken>`.

**Behavior (server must):**
1. Authenticate the user (via the Bearer token / session). **Never** delete based on body `id`/`email` alone — verify the authenticated user matches.
2. **Permanently delete** the account and all associated data:
   - user profile / credentials
   - their questions (`content/ask` submissions / my-questions)
   - bookmarks (`user/bookmark/*` linked records)
   - notifications / push subscriptions (`notification/subscribe` tokens)
   - any other PII
3. Optionally: revoke/expire their token(s).
4. Do **not** just soft-disable/deactivate — App Review requires permanent deletion (temporary deactivation is insufficient).

**Success response:**
```json
{ "success": true, "message": "Your account has been deleted." }
```

**Error responses:**
```json
{ "success": false, "message": "User not found." }        // HTTP 404
{ "success": false, "message": "Unauthorized." }          // HTTP 401
{ "success": false, "message": "Something went wrong." }  // HTTP 500
```

The iOS app:
- On `success === true` → clears local data and restarts to the login screen.
- On failure → shows `responseJson.message` (or a fallback) to the user.

### Confirmation flow
The app shows an in-app confirmation dialog before calling the endpoint, which satisfies the "confirmation steps" allowance. No email/phone/customer-service requirement is imposed (fine for non-regulated apps).

---

## 3. Test checklist
- Guest (no token): `content/posts`, `content/categories`, `content/banners`, `content/post`, `content/search` return data when `X-App-Key` + `X-Device-Id` are correct.
- Same requests with wrong/missing `X-App-Key` → 401.
- Same requests exceeding rate limit → 429.
- Authenticated user endpoints still work with `Authorization` + the two app headers.
- `ty=user/delete` with a valid token deletes the account and returns `success: true`; a second call returns "User not found".
