aca9e8d155
## Summary
First PR of the **portal-admin User-list chantier** per [ADR-0020](docs/decisions/0020-portal-admin-app.md) §"v1 scope — User list (read-only)". Ships the **write side** only:
1. A new `public.users` table that holds the BFF's local cache of identities seen sign in to either portal-shell or portal-admin.
2. A `UserDirectoryService.recordSignIn(user)` upsert called from `SessionEstablisher.establish` after the blocking audit write.
The read side (`GET /api/admin/users` + the admin viewer SPA screen) lands in two follow-up PRs of the same chantier.
## Schema
[`prisma/schema.prisma`](apps/portal-bff/prisma/schema.prisma) gains a `User` model in the `public` schema:
| Column | Type | Notes |
| --- | --- | --- |
| `oid` | TEXT, PK | Entra's stable per-user identifier inside the tenant. Per-tenant uniqueness is sufficient for v1's single-workforce-tenant design (ADR-0008). |
| `tid` | TEXT | Tenant id. Updated on every upsert because a dual-audience future may legitimately change it. |
| `audience` | TEXT | `'workforce'` \| `'customer'`. Hardcoded to `workforce` in v1 per ADR-0008's simplification; will read from session/claims when External ID activates. |
| `username` | TEXT | Updated on every upsert (Entra-side rename possible). |
| `display_name` | TEXT | Same. |
| `first_seen_at` | TIMESTAMPTZ | Set once at first sign-in via DEFAULT NOW(); **never overwritten** thereafter. Enables "users since <date>" without joining anything. |
| `last_seen_at` | TIMESTAMPTZ | Updated on every upsert. Enables "most recently active" without scanning `audit.events`. |
Indexes:
- `last_seen_at DESC` — admin default sort.
- `username` — prefix filtering.
Migration in [`prisma/migrations/20260514192014_users_directory/`](apps/portal-bff/prisma/migrations/20260514192014_users_directory/migration.sql).
## [`UserDirectoryService`](apps/portal-bff/src/users/user-directory.service.ts)
```ts
async recordSignIn(entry): Promise<void> {
try {
await prisma.user.upsert({
where: { oid },
create: { oid, tid, audience, username, displayName },
update: { tid, audience, username, displayName, lastSeenAt: new Date() },
});
} catch (err) {
// logged, never propagated
}
}
```
**Best-effort write.** Catches its own errors, logs a Pino warn (`user_directory.record_sign_in_failed`), returns `undefined`. The directory is a convenience for admin browsing, not a security boundary — a Postgres hiccup must not lock a user out of sign-in. ADR-0013's "no audit ⇒ no action" applies to the audit module only.
## [`SessionEstablisher`](apps/portal-bff/src/auth/session-establisher.service.ts) wiring
The directory call lands right after the existing audit emission:
```ts
await this.audit.signIn({ actor: user, sessionId: req.sessionID }); // blocking per ADR-0013
await this.userDirectory.recordSignIn({ ...user, audience: 'workforce' }); // best-effort
this.logger.log(...);
```
Two invariants the tests pin:
1. **Audit-first**: when `audit.signIn` throws, `userDirectory.recordSignIn` is NOT called. The directory never holds a row for a sign-in the audit log doesn't carry.
2. **Awaited**: an admin who just signed in sees themselves on the user list immediately — no race between the upsert and the response.
## Module wiring
[`UsersModule`](apps/portal-bff/src/users/users.module.ts) is declared `@Global()` so `SessionEstablisher` (which lives in `AuthModule`) injects `UserDirectoryService` without forcing `AuthModule` to import `UsersModule`. The directory is a true cross-cutting concern: one writer (the auth callback) and one future reader (the admin endpoint).
Wired into [`AppModule`](apps/portal-bff/src/app/app.module.ts) alongside the other v1 modules. `auth.module.spec.ts` updated to also import `UsersModule` in its slice-of-graph compile (otherwise the test fails to resolve the new `SessionEstablisher` dep).
## Notes for the reviewer
- The directory write **awaits** (not fire-and-forget). The cost is one round-trip per sign-in on the response-critical path; the benefit is the no-race property called out above. If sign-in p95 becomes an issue we can revisit (e.g. background job) but the simpler shape is correct first.
- `firstSeenAt` is intentionally absent from the `update` payload. The Prisma upsert's `update` block is precisely what changes on conflict; omitting the field leaves it untouched at the column level (Postgres-side default doesn't refire on UPDATE).
- The model lives in `public`, not in a dedicated `identity` or `cms` schema. ADR-0020 enumerates `cms.*` for editorial data and `audit.*` for the audit ledger but doesn't require a separate schema for user-directory data. We can promote it to its own schema later if a role-isolation need emerges; the migration would be a `ALTER TABLE users SET SCHEMA …`.
- `audit.events.actor_id_hash` is **not** stored on `public.users`. A future admin endpoint that joins sign-in counts from `audit.events` can compute the hash on-the-fly via `HashUserIdService` — keeping the salted-hash invariant from ADR-0013 intact (the salt stays inside the audit module).
## Test plan
- [x] `pnpm nx test portal-bff` — **365 specs pass** (was 358; +7: UserDirectoryService 4, SessionEstablisher integration 3).
- [x] `pnpm exec nx affected -t format:check lint test build --base=origin/main` — clean (the pre-existing rate-limit warnings + one unused-eslint-disable from PR #137 are unrelated).
- [x] Prisma `migrate diff` confirms the model matches the migration SQL.
- [ ] e2e — after merge: sign in via portal-shell or portal-admin, expect a row in `public.users` with the right `oid` / `last_seen_at`; sign in again, expect the same row's `last_seen_at` to advance and `first_seen_at` to stay put.
## What's next
The chantier sequence:
1. **This PR** — write side: schema + service + sign-in upsert.
2. **PR 2** — BFF `GET /api/admin/users` (paginated + filterable, gated by `@RequireAdmin`, emits `admin.users.query` audit).
3. **PR 3** — portal-admin `/users` screen (table + filter form), promote the sidebar entry from "Soon" badge to live link.
---------
Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #140
113 lines
3.6 KiB
TypeScript
113 lines
3.6 KiB
TypeScript
import type { Logger } from 'nestjs-pino';
|
|
import type { PrismaService } from 'nestjs-prisma';
|
|
import { UserDirectoryService, type UserDirectoryEntry } from './user-directory.service';
|
|
|
|
interface PrismaStub {
|
|
user: {
|
|
upsert: jest.Mock;
|
|
};
|
|
}
|
|
|
|
function makeLogger() {
|
|
return { log: jest.fn(), warn: jest.fn(), error: jest.fn() } as unknown as Logger & {
|
|
log: jest.Mock;
|
|
warn: jest.Mock;
|
|
error: jest.Mock;
|
|
};
|
|
}
|
|
|
|
function makeSubject(opts?: { upsert?: jest.Mock }): {
|
|
service: UserDirectoryService;
|
|
prisma: PrismaStub;
|
|
logger: ReturnType<typeof makeLogger>;
|
|
} {
|
|
const prisma: PrismaStub = {
|
|
user: {
|
|
upsert: opts?.upsert ?? jest.fn().mockResolvedValue(undefined),
|
|
},
|
|
};
|
|
const logger = makeLogger();
|
|
const service = new UserDirectoryService(prisma as unknown as PrismaService, logger);
|
|
return { service, prisma, logger };
|
|
}
|
|
|
|
const ENTRY: UserDirectoryEntry = {
|
|
oid: 'user-oid',
|
|
tid: 'tenant-1',
|
|
username: 'jane.doe@apf.example',
|
|
displayName: 'Jane Doe',
|
|
audience: 'workforce',
|
|
};
|
|
|
|
describe('UserDirectoryService.recordSignIn', () => {
|
|
it('issues an upsert keyed by oid with the right create / update payloads', async () => {
|
|
const { service, prisma } = makeSubject();
|
|
await service.recordSignIn(ENTRY);
|
|
expect(prisma.user.upsert).toHaveBeenCalledTimes(1);
|
|
const args = prisma.user.upsert.mock.calls[0]?.[0] as {
|
|
where: { oid: string };
|
|
create: Record<string, unknown>;
|
|
update: Record<string, unknown>;
|
|
};
|
|
expect(args.where).toEqual({ oid: 'user-oid' });
|
|
expect(args.create).toEqual({
|
|
oid: 'user-oid',
|
|
tid: 'tenant-1',
|
|
audience: 'workforce',
|
|
username: 'jane.doe@apf.example',
|
|
displayName: 'Jane Doe',
|
|
});
|
|
// Update path: refreshes every mutable field + bumps lastSeenAt;
|
|
// crucially does NOT include `firstSeenAt` so it stays
|
|
// immutable after first sign-in.
|
|
expect(args.update).toEqual(
|
|
expect.objectContaining({
|
|
tid: 'tenant-1',
|
|
audience: 'workforce',
|
|
username: 'jane.doe@apf.example',
|
|
displayName: 'Jane Doe',
|
|
}),
|
|
);
|
|
expect(args.update['firstSeenAt']).toBeUndefined();
|
|
expect(args.update['lastSeenAt']).toBeInstanceOf(Date);
|
|
});
|
|
|
|
it('updates `displayName` + `username` if either changed since the previous sign-in', async () => {
|
|
const { service, prisma } = makeSubject();
|
|
await service.recordSignIn({
|
|
...ENTRY,
|
|
displayName: 'Jane Updated',
|
|
username: 'jane2@apf.example',
|
|
});
|
|
const args = prisma.user.upsert.mock.calls[0]?.[0] as {
|
|
update: Record<string, unknown>;
|
|
};
|
|
expect(args.update['displayName']).toBe('Jane Updated');
|
|
expect(args.update['username']).toBe('jane2@apf.example');
|
|
});
|
|
|
|
it('swallows Prisma errors and logs them — never propagates (sign-in must succeed)', async () => {
|
|
const upsert = jest.fn().mockRejectedValue(new Error('connection refused'));
|
|
const { service, logger } = makeSubject({ upsert });
|
|
await expect(service.recordSignIn(ENTRY)).resolves.toBeUndefined();
|
|
expect(logger.warn).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
event: 'user_directory.record_sign_in_failed',
|
|
oid: 'user-oid',
|
|
reason: 'connection refused',
|
|
}),
|
|
'UserDirectoryService',
|
|
);
|
|
});
|
|
|
|
it('logs the underlying message verbatim when the rejection is not an Error', async () => {
|
|
const upsert = jest.fn().mockRejectedValue('some string');
|
|
const { service, logger } = makeSubject({ upsert });
|
|
await service.recordSignIn(ENTRY);
|
|
expect(logger.warn).toHaveBeenCalledWith(
|
|
expect.objectContaining({ reason: 'some string' }),
|
|
'UserDirectoryService',
|
|
);
|
|
});
|
|
});
|