# Firebase / Firestore security rules

## Why this exists

The Next.js frontend embeds the Firebase Web SDK and reads Firestore **directly**
from the browser (`useFirebaseNotifications`, `attendance-monitor`). Firestore
Security Rules are therefore the *only* thing between a visitor and other tenants'
notification data. The project id ships in the client bundle, so anyone can hit
the Firestore REST API — open rules mean full read (and possibly write) of every
user's notifications.

## How auth works now

1. On login / token refresh the API returns `firebaseToken` — a Firebase custom
   token minted by `FirebaseService::createCustomToken()` with
   `uid = "user_<userId>"`.
2. The frontend calls `signInWithCustomToken()` (see `src/lib/firebase.ts`).
3. `firestore.rules` checks `request.auth.uid` against the document path.
4. The backend writes with the service account and is unaffected by rules.

## Deploy the rules

```bash
cd firebase
firebase login
firebase use <project-id>        # e.g. emsapp-a2ce1
firebase deploy --only firestore:rules
```

Do this for **every** Firebase project (one per client, if applicable).

## Verify

Anonymous read must now fail:

```bash
curl "https://firestore.googleapis.com/v1/projects/<project-id>/databases/(default)/documents/notifications/user_1/notifications"
# expect: 403 PERMISSION_DENIED
```

Signed-in read of another user's path must also fail — test with a custom token
for `user_1` requesting `notifications/user_2/...`.

## Enable Firebase Authentication

In the Firebase console: Authentication → Sign-in method → enable **Custom / any**
provider so `signInWithCustomToken` is accepted. No other provider is needed.
