# Auth, users and onboarding (Prompt 1)

## Endpoints (`/api/v1`)

### Public (`throttle:auth` unless noted)

| Method | Path | Body | Result |
| --- | --- | --- | --- |
| POST | `auth/register` | `name` + `phone` **or** `email`+`password`+`password_confirmation` | 202; pending reader, code sent by SMS/e-mail |
| POST | `auth/otp/verify` | `target`, `code`, `device_id?`, `device_name?` | activates reader → `AuthResource` (signed in) |
| POST | `auth/otp/send` (`throttle:otp`) | `target`, `purpose` = `register` \| `login` \| `password_reset` | 202 always |
| POST | `auth/register/reporter` | multipart: `name`, `email`/`phone`, `password`(+confirmation), `district`, `district_id?`, `experience`, `samples[]`, `documents[]` (pdf/jpg/png/webp ≤5 MB, ≤5) | 201 application (pending contributor) |
| POST | `auth/login` | `login` (email/username/phone), `password` | `AuthResource` (`token` / `session` / `two_factor_challenge`) |
| POST | `auth/login/otp` | `phone`, `code` | `AuthResource` |
| POST | `auth/2fa/challenge` | `challenge_token`, `code` (e-mailed or TOTP) \| `recovery_code` | `AuthResource` |
| POST | `auth/2fa/challenge/resend` | `challenge_token` (e-mail challenges only) | 202; 3 sends per 10 min |
| POST | `auth/refresh` (`throttle:public`) | `refresh_token` | rotated `AuthResource` |
| POST | `auth/password/forgot` | `email` \| `phone` | 202 always (link to `CMS_FRONTEND_URL/reset-password?token&email`, or SMS code) |
| POST | `auth/password/reset` | `email`+`token` \| `phone`+`code`, `password`(+confirmation) | 200; all sessions/tokens revoked |
| GET | `auth/invitations/{token}` | — | invitation (masked contact, role) · 404 · 410 |
| POST | `auth/invitations/accept` | `token`, `name`, `username`, `password`(+confirmation) | staff account + `AuthResource` |
| POST | `auth/logout` (`auth:sanctum`) | `all?` | 204 |

### Signed in (`auth:sanctum`, `active`, `throttle:cms`)

| Method | Path | Notes |
| --- | --- | --- |
| GET/PATCH | `me` | profile: `name`, `username`, `designation`, `bio` ({ne,en}), `preferred_locale` |
| PUT | `me/password` | `current_password`, `password`(+confirmation); other devices signed out |
| GET | `me/devices`, `me/devices/{id}` | `current` flag marks this token/session |
| PATCH | `me/devices/{id}` | `name`, `trusted` |
| DELETE | `me/devices/{id}` | signs that device out |
| POST | `me/2fa/enable` | `secret`, `otpauth_url` (render as QR) |
| POST | `me/2fa/email-code` (`throttle:otp`) | e-mail mode: sends a step-up code | 202 |
| POST | `me/2fa/confirm` | `code` → recovery codes (first time) / re-confirm for 15 min (TOTP, or the e-mailed code) |
| DELETE | `me/2fa` | `code` (TOTP or recovery); refused for 2FA-required roles |
| GET | `me/2fa/recovery-codes` | needs `2fa.recent` |

### CMS (`auth:sanctum`, `active`, `ability:cms`, `2fa.required`, `super-admin`, `throttle:cms`)

| Method | Path | Notes |
| --- | --- | --- |
| GET | `cms/users` | `filter[type|status|role|is_verified_reporter|search]`, `sort=±created_at|±last_login_at|±username`, `per_page` |
| POST | `cms/users` | create (default staff/active; random password if omitted) |
| GET/PATCH | `cms/users/{uid}` | update; password change signs the user out everywhere |
| POST | `cms/users/{uid}/suspend` · `reactivate` · `force-logout` · `reset-2fa` | `reason?`; need `2fa.recent` |
| POST | `cms/invitations` | `email`/`phone`, `role` (existing role), `scopes[{type,key}]`, `name?` |
| GET | `cms/reporter-applications` | `status?`, `per_page?` |
| POST | `cms/reporter-applications/{id}/approve` | `role` = `reporter` \| `stringer`, `notes?` |
| POST | `cms/reporter-applications/{id}/reject` | `reason` |

## Permissions

CMS routes use the `access.users.*` and other catalogue permissions. Horizon, Telescope
and API docs use `system.horizon`, `system.telescope` and `api-docs.view`. Role-based
2FA and dangerous permission confirmation are enforced. See [access.md](access.md).

## Flows

* **Reader by phone**: `register` → SMS code → `otp/verify` → active + signed in.
* **Reader by e-mail**: `register` (with password) → e-mailed code → `otp/verify`.
  Re-registering an unverified reader updates it and resends the code.
* **Reporter application**: contributor account is `pending` until approved; approval sets
  `active`, `is_verified_reporter`, `approved_role` and assigns the role and district scope through `AccessService`.
* **Staff invitation**: 64-char single-use token (sha256 at rest), 72 h, earlier pending
  invitations to the same contact revoked. Accept creates an active staff user (contact marked
  verified), assigns the role, applies scopes through `AccessService`, and fires `StaffInvitationAccepted`.
* **Super-admin OTP switch**: `SUPER_ADMIN_OTP_ENABLED=true` (default) requires a
  password followed by a 6-digit e-mail OTP, irrespective of `TWO_FACTOR_METHOD`.
  No authenticator enrolment is needed; a missing e-mail returns 409
  `two_factor_email_unavailable`. Set `SUPER_ADMIN_OTP_ENABLED=false` for password-only
  super-admin login and no recent-verification prompts on CMS, role assignment or
  workflow actions. This applies even if the user previously enrolled TOTP; stored
  secrets, recovery codes and role metadata are preserved. Password validation,
  account status, permissions, scopes, throttles and auditing still apply.
  Other roles retain their configured 2FA behavior.
  With OTP off, `auth/login` returns `mode: session` or `token`, a populated `user`,
  and `two_factor_required: false`, `two_factor_enrollment_required: false`.
  With OTP on, the response is `mode: two_factor_challenge`, `user: null`,
  `two_factor_required: true`, `two_factor_method: email`, and no access token.
  Submit `{"challenge_token": "<from login>", "code": "123456"}` to
  `POST /api/v1/auth/2fa/challenge`; success returns the normal session/token response.
  Resend with `POST /api/v1/auth/2fa/challenge/resend`. Codes and challenges expire
  after 5 minutes by default, and e-mails run on the `high` queue.
  Re-enabling OTP restores challenges for subsequent logins and recent-verification
  checks for sensitive actions; existing sessions are not automatically revoked.
* **2FA enrolment for required roles**: login succeeds with `two_factor_enrollment_required: true`;
  `cms/*` answers 403 until `me/2fa/enable` + `me/2fa/confirm`.
* **E-mail 2FA (`TWO_FACTOR_METHOD=email`)**: for users whose role requires 2FA (or who enrolled
  TOTP) and who have an e-mail, login answers `two_factor_challenge` with `two_factor_method: email`
  and e-mails a 6-digit code (`otp_codes`, purpose `two_factor`, 5 min, 5 attempts).
  `auth/2fa/challenge` accepts that code (or an enrolled TOTP / recovery code);
  `auth/2fa/challenge/resend` sends a new one. No enrolment is needed (`User::hasSecondFactor()`).
  Dangerous actions: `me/2fa/email-code` → `me/2fa/confirm` with the code. Staff without an e-mail
  fall back to TOTP enrolment. `TWO_FACTOR_METHOD=totp` (default) keeps the authenticator-only flow.
* **SMS codes off (`OTP_SMS_ENABLED=false`)**: `otp/send` to a phone, `login/otp`, phone sign-up and
  phone password reset answer 422 `sms_otp_disabled` before anything is written; e-mail codes work.

## Events

| Event | Fired when | Listeners |
| --- | --- | --- |
| `Events\Auth\ReporterApplicationDecided` | approve/reject committed | Access applied synchronously by AccessService |
| `Events\Auth\StaffInvitationAccepted` | invitation accepted | Access applied synchronously by AccessService |
| `Events\Auth\UserSuspended` | suspension committed | — |

## Audit actions (`App\Enums\AuditAction`)

login, login_otp, failed_login, account_locked, logout, logout_all, token_refreshed,
refresh_token_reuse, 2fa_challenge_passed/failed, 2fa_recovery_code_used, registered,
contact_verified, otp_sent, otp_failed, profile_updated, password_changed,
password_reset_requested, password_reset, password_reset_failed, 2fa_enabled, 2fa_confirmed,
2fa_disabled, 2fa_reset, device_new/renamed/trusted/revoked, user_created/updated/suspended/
reactivated/force_logged_out, invite_sent, invite_accepted, application_submitted,
application_decided.

## Tables

`users` (ULID `uid`, translatable `name/designation/bio`, encrypted `phone` + HMAC `phone_hash`,
argon2id `password`, encrypted 2FA columns, soft deletes; `home_*_id` FKs arrive in Prompt 2),
`user_devices`, `personal_access_tokens` (+`device_id`), `refresh_tokens`, `otp_codes`,
`login_attempts`, `staff_invitations`, `reporter_applications` (+ media collection `documents`
on `media_private`), `audit_events`, `seed_versions`. Avatar = media collection `avatar`
(single file, `media_public`, queued `thumb` conversion).

## Settings (`config/paschim.php`, env)

`ACCESS_TOKEN_TTL` (60), `REFRESH_TOKEN_TTL_DAYS` (30), `PASSWORD_BREACH_CHECK`,
`SANCTUM_STATEFUL_DOMAINS`, `CORS_ALLOWED_ORIGINS`, `CMS_FRONTEND_URL`, `WEB_FRONTEND_URL`,
`SMS_DRIVER` (`log`|`sparrow`|`aakash`) + `SPARROW_SMS_TOKEN/FROM`, `AAKASH_SMS_TOKEN`,
`UPLOAD_SCANNER`, `CLAMAV_SOCKET`, `TWO_FACTOR_ISSUER`, `TWO_FACTOR_METHOD` (`totp`|`email`),
`OTP_SMS_ENABLED`, `SUPER_ADMIN_OTP_ENABLED` (true); lockout 5/15 min, OTP 6 digits/5 min/5
attempts/3 sends per 10 min, invitations 72 h, 2FA-required roles and the recent-confirmation window.

## Seeders

`SuperAdminSeeder` (via `DatabaseSeeder`): upsert by `SUPER_ADMIN_EMAIL`; creates role
`super-admin` (guard `web`); password only set on creation; production requires a strong,
non-breached password; audited; recorded in `seed_versions` (`2026.11.1`).

## Not in Prompt 1 (follow-ups)

* Avatar upload endpoint (media prompt; collection already defined).
* Changing e-mail/phone from `PATCH /me` (needs a verify-new-contact flow; `OtpPurpose::VerifyContact` exists).
* Push tokens on devices (Flutter prompt).

## Applying authentication configuration

Set `SUPER_ADMIN_OTP_ENABLED=false` for direct super-admin password login, or `true`
to require an e-mailed OTP. Then run:

```sh
php artisan config:cache
php artisan horizon:terminate
```

The process manager must restart Horizon after graceful termination. For local
`queue:work` workers, use `php artisan queue:restart` instead. An unset switch
defaults to true; no database migration or reseeding is needed.

## OTP e-mail delivery

OTP notifications are encrypted queued jobs on `high`, using the configured mailer.
Run `php artisan horizon` in a separate terminal, or use `composer dev`, which starts
Horizon alongside the API. A default-only queue worker does not deliver these codes.
Use `php artisan horizon:status` and `php artisan queue:failed` to diagnose stalled
delivery. SMTP credentials must be configured and `MAIL_MAILER=smtp` must be selected
for SMTP delivery; `log` and `array` do not deliver to an inbox.

After starting the workers, request a fresh code: existing codes expire after five
minutes even if their e-mail was waiting in the queue. Super-admin login does not
generate a code when `SUPER_ADMIN_OTP_ENABLED=false`.
