# Authentication

Dashboard authentication is live-only. Browser requests go to this app's same-origin `/api/auth/*` handlers, which validate requests and forward them to the TIAR API. When auth configuration is missing or invalid, sign-in and account-recovery screens report that authentication is unavailable, and dashboard routes redirect to sign-in. The app never simulates OTP, login, recovery, reset, or password setup success. Customer/profile reads, voucher management, payment account and channel management, transaction and withdrawal reads, and loyalty operations use authenticated server-side routes; API failures are surfaced without substituting fixture success.

## Dashboard menu and page access

After validating the session, the server reads `GET /v1/admin/tenant/menus?app_code=MONET` with the same bearer token and TIAR headers. An enabled `view` permission for the session role grants the existing dashboard patterns listed in that menu's `routes`. Detail routes such as `/locations/[id]` require their own grant. Query parameters do not change the required route permission.

The sidebar keeps its local layout and displays only permitted pages. Each dashboard page checks the same permissions before reading feature data. A failed menu request blocks page access and can be retried. If Dashboard lacks a grant, the sign-in landing page chooses the first available link in navigation order. Resource scope and operation permissions continue to be enforced by the backend.

## Server configuration

Supply the server settings from the approved deployment configuration. `MONETIZATION_PUBLIC_ORIGIN` is the public origin of this app and is used by same-origin request checks when a reverse proxy makes the server-side request URL differ from the browser-visible URL.

| Setting | Purpose |
| --- | --- |
| `MONETIZATION_API_BASE_URL` | Server-side API base URL. The app appends the versioned auth, user, admin analytics, voucher, payment, or loyalty path. Production requires HTTPS. |
| `MONETIZATION_PUBLIC_ORIGIN` | Public origin of this app, such as `https://dev.monet.parkingplus.ai`, without a path. Used to validate browser request origins behind a reverse proxy. If omitted, the app falls back to the request URL origin. |
| `MONETIZATION_FORWARDED_HOST` | Host value sent in the `x-forwarded-host` header. Configure the host expected by the API, without a URL scheme. |
| `MONETIZATION_APP_NAME` | App value sent in the `x-app-name` header and checked against the returned session claims. |

When the API base URL is blank or absent, authentication is unavailable and dashboard entry fails closed. When it is set, the forwarded host and app name must also be valid; incomplete or invalid configuration fails closed. Keep these variables server-side and out of `NEXT_PUBLIC_*` variables and client bundles.

## Roles and API flow

The only supported roles are `admin`, `site_manager`, and `investor`. The UI label `site-manager` maps to the API value `site_manager`; `investor` is sent as `investor`. Operator and other role values are rejected. A validated session supplies the dashboard role. URL parameters cannot select or change the authenticated role.

The browser posts to same-origin `/api/auth/{action}` routes. The server forwards supported actions to `/v1/admin/auth/{action}` and sends the configured `x-forwarded-host` and `x-app-name` headers. Sign-in and OTP requests pass only validated role values; the OTP adapter maps `role` to the API field `role_name`. Forgot-password and reset flows use the corresponding reset actions. Password setup, password changes, and logout use the access token from the server-managed session cookie; refresh uses both stored tokens. OTP email links are verified through the same upstream `verify` action.

The customer and profile screens use these read-only user operations:

| Screen | Upstream route | Behavior |
| --- | --- | --- |
| `/customers` | `GET /v1/admin/users` | Server-side customer list with role, search, filters, sort, and pagination. |
| Dashboard account menu and `/profile` | `GET /v1/admin/users/me` | The session-validation response is reused for safe profile display fields; no second profile request is made. |

The customer list and `/customers/[id]` detail are fetched on the server with the authenticated bearer token and configured headers, using `GET /v1/admin/users` and `GET /v1/admin/users/{id}`. Customer details are read-only and show validated identity, profile, address, and wallet fields. Filtered CSV export uses a same-origin handler and the same validated query. Failed or unsupported responses show an error without substituting fixture records. The profile page shows only validated identity and address fields and is read-only. Password changes continue through the existing authenticated auth route.

Payment account configuration follows the same server-side boundary. The browser calls same-origin `/api/payment/*` route handlers. They require the current server-validated session, reject cross-origin requests, take the bearer token from the HttpOnly cookie, and forward calls to `/v1/monet/payment/*` with the configured headers. The server disables caching and removes merchant keys/secrets from upstream response bodies. It never sends a merchant secret back to the browser. API failures are shown and do not fall back to mock success.

The Loyalty Management page calls same-origin `GET/PATCH /api/loyalty/settings` and `GET /api/loyalty/points/ledger` handlers. They apply the same origin and session checks, then forward to the corresponding `/v1/monet/loyalty/*` routes. API failures do not fall back to sample settings or a simulated tenant ledger.

The Vouchers page calls same-origin `GET/POST /api/vouchers`, `GET/PATCH/DELETE /api/vouchers/{id}` handlers. These routes require an admin session, validate voucher create/update fields, and forward to `GET/POST /v1/monet/vouchers` and `GET/PATCH/DELETE /v1/monet/vouchers/{id}`. Voucher creation and updates require a positive `reward_value` and a `reward_unit` of `FIXED` or `PERCENTAGE`; energy price subsidy also requires `target_energy_price`. Add Voucher option lookups use same-origin `GET /api/vouchers/options`: location choices come from the admin location directory, and customer choices use the paginated `GET /v1/admin/users?role=user` list. The lookup route returns only location IDs/names or customer IDs/names/emails, requires an admin session, and does not cache responses. The voucher list does not fall back to fixtures when the API fails.

The Dashboard loads `GET /v1/admin/ocpp/sessions/top_chargepoint` twice with `created_atGte`, `created_atLte`, and `total_chargepoints=10`: `sort_order=desc` for the highest-revenue chargepoints and `sort_order=asc` for the lowest-revenue chargepoints. It also loads `GET /v1/admin/ocpp/sessions/top_location` twice with `total_locations=10`: `sort_order=desc` for the highest-revenue locations and `sort_order=asc` for the lowest-revenue locations. Both rankings use the same date filter, which defaults to the current month through today and can be changed by the user. The page shows both rankings and their revenue breakdowns, displays the shared total revenue once, and uses red for the lowest-revenue charts. The Revenue & Cost Analysis page loads `GET /v1/admin/ocpp/sessions/revenue` with `revenue_type` and `GET /v1/admin/ocpp/sessions/cost` with `cost_summary_type`, in addition to `created_atGte` and `created_atLte`. Both grouping parameters accept `daily`, `weekly`, `monthly`, or `yearly` and default to `daily`; the Group By control sends the selected interval to each endpoint. The page shows the revenue, energy bill, and profit totals from the revenue response, plus the total, energy, time, and idle cost values and category summaries from the cost response. Each endpoint reports errors independently, and the cost category totals are presented as returned by the API. User & Behavior Analysis loads `GET /v1/admin/ocpp/sessions/active_users` with those date parameters and `active_users_summary_type=active_users.daily`. These reports are fetched by server-side page loaders using the validated session and matching analytics menu permission and are not cached. The behavior page shows the unique active-user total and daily activity. Revenue, cost, and active-users summary endpoints do not accept location filters; Dashboard location rankings use the separate top_location endpoint. API errors are shown in the same view for all permitted roles.

The Monet screens use these upstream operations:

| Operation | Upstream route |
| --- | --- |
| List payment gateways | `GET /v1/monet/payment/gateways` |
| List/create accounts | `GET/POST /v1/monet/payment/accounts` |
| Update an account and its active state | `PATCH /v1/monet/payment/accounts/{id}` |
| Read/enable connected channels | `GET/POST /v1/monet/payment/accounts/{id}/channels` |
| Disable a connected channel | `DELETE /v1/monet/payment/accounts/{id}/channels/{channel_id}` |
| List available channels for a gateway | `GET /v1/monet/payment/gateways/{gateway_id}/channels` |
| Update withdrawal admin fee | `PATCH /v1/monet/payment/accounts/fees` |
| List transactions | `GET /v1/monet/payment/transactions` |
| List withdrawal requests | `GET /v1/monet/payment/withdrawals` |
| Read a withdrawal request | `GET /v1/monet/payment/withdrawals/{id}` |
| Read/update loyalty settings | `GET/PATCH /v1/monet/loyalty/settings` |
| Read tenant points ledger | `GET /v1/monet/loyalty/points/ledger` |
| List/create vouchers | `GET/POST /v1/monet/vouchers` |
| Read/update/delete voucher | `GET/PATCH/DELETE /v1/monet/vouchers/{id}` |

The account-management UI uses the gateway list to let users select a provider when creating an account, then uses the account routes above to save its credentials. Connected channels come from the account's channel route; available active channels come from the gateway catalog route and can be linked to the account. Transaction History and the withdrawal request page use their list operations for read-only paginated tables. The Loyalty Management page reads and updates loyalty settings and displays the tenant points ledger. The Vouchers page lists, reads details, creates, updates, and deletes vouchers. Withdrawal approval, rejection, payout, and proof upload are not part of this API integration.

Dashboard requests validate the access token against `/v1/admin/users/me`. Missing, expired, unsupported, or unauthorized sessions are redirected to sign-in or password setup as appropriate. The browser only receives safe session display data and the separately parsed profile fields; access and refresh tokens are never passed to client components. Tokens are stored in HttpOnly, SameSite=Lax cookies; cookies are Secure in production. Auth handlers reject cross-origin requests, avoid caching auth responses, and surface failures instead of reporting a successful preview.

## Fixture data and verification limits

When auth configuration is absent, no auth request is sent and no local success is reported; dashboard routes are unavailable. Fixture-backed product pages remain part of the application for authenticated development. Integrated analytics, voucher, payment, and loyalty requests surface upstream failures instead of applying local fixture success.

Local tests and browser QA use mocked API responses only. They do not verify that a live TIAR user/auth/payment deployment accepts these requests, which customer and profile fields a real account returns, that an actual user has the required payment features, or that OTP and password-reset messages reach an inbox. Those external behaviors require the deployed API configuration, an eligible test account, and access to the corresponding email inbox.
