Un rafraîchissement (F5) sur /admin/monitoring affichait le JSON brut de
l'API au lieu de la page — même chose à craindre pour tout futur /admin/*
GET sans segment supplémentaire.
Cause : `server.mountRouter("/admin", adminRouter)` (app.ts) montait
l'API admin exactement sous /admin, la même racine que les pages
/admin/* d'apps/web, servies depuis la même origine/le même process en
prod (image Docker unique). Express matche par chemin, sans égard au
Accept — `GET /admin/monitoring` (route API) et la page du même nom
étaient en conflit direct ; l'API gagnait systématiquement (montée
avant serveStaticFrontend), donc chaque F5 sur cette page recevait le
JSON de l'API plutôt que index.html.
Seule /admin/monitoring collidait réellement aujourd'hui (seul
sous-routeur admin à répondre GET sur sa racine bare) mais le
mécanisme touche toute future route admin nommée comme sa page — d'où
un correctif structurel plutôt qu'un renommage ponctuel.
Correctif : l'API admin est montée sous /admin/api (app.ts), jamais
bare /admin. Toute la surface admin bouge en conséquence
(auth/metrics/monitoring/tech-steps/catalog) ; les pages front
(/admin/monitoring, /admin/catalogue, /admin/corrections...) sont
inchangées, seul admin-client.ts change de base URL. Mis à jour en
cohérence : commentaires JSDoc citant les routes (apps/api + apps/web +
packages/shared), specs/backend-architecture.md,
specs/batch-cooking-modele.md, les intercepts Cypress (globs + un
matcher regex qui avait échappé au premier passage) et les chemins
supertest du suite Mocha admin-*.test.ts.
Simplifie au passage admin-monitoring.cy.ts : le contournement
resourceType ajouté en #32 pour cette même collision n'a plus lieu
d'être une fois les chemins distincts (retour à un intercept déclaratif
simple) — le bug Cypress/Chrome qu'il avait mis au jour reste noté en
commentaire pour référence future.
Vérifié : pnpm lint clean ; build api+web clean ; suite e2e complète
28/28 fichiers, 116/116 tests verts (dont les 16 tests admin-*).
Suite Mocha apps/api non exécutable cette session (Postgres/Docker
injoignable) — chemins mis à jour mécaniquement en cohérence avec le
nouveau mount point, à faire tourner en CI/à la prochaine session avec
accès DB.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
71 lines
2.6 KiB
TypeScript
71 lines
2.6 KiB
TypeScript
import type { AdminLoginInput, AdminUserView } from "@batch-cooking/shared";
|
|
import { createContext, type ReactNode, useCallback, useContext, useEffect, useState } from "react";
|
|
import { adminApiClient } from "../../api/admin-client";
|
|
|
|
/** Auth state/actions exposed via {@link useAdminAuth} — the admin-app counterpart of apps/web's `AuthContext`. */
|
|
interface AdminAuthContextValue {
|
|
/** Currently authenticated admin, or `null` if no active session. */
|
|
admin: AdminUserView | null;
|
|
/** True only while the initial `GET /admin/api/auth/me` check is pending — lets `RequireAdmin` avoid a premature redirect. */
|
|
isLoading: boolean;
|
|
/** Verifies credentials and updates `admin` on success. Throws `ApiError` on failure. */
|
|
login: (input: AdminLoginInput) => Promise<void>;
|
|
/** Ends the session and clears `admin`. */
|
|
logout: () => Promise<void>;
|
|
}
|
|
|
|
const AdminAuthContext = createContext<AdminAuthContextValue | null>(null);
|
|
|
|
/**
|
|
* Provides admin authentication state to the whole app. On mount, calls
|
|
* `GET /admin/api/auth/me` once to restore the session from the `admin_session`
|
|
* httpOnly cookie (if any) — same "reload keeps you logged in" behaviour as
|
|
* apps/web's `AuthProvider`.
|
|
*/
|
|
export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
|
const [admin, setAdmin] = useState<AdminUserView | null>(null);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
|
|
useEffect(() => {
|
|
adminApiClient
|
|
.me()
|
|
.then(setAdmin)
|
|
// No/invalid session — the normal state for a first visit, not an error.
|
|
.catch(() => setAdmin(null))
|
|
.finally(() => setIsLoading(false));
|
|
}, []);
|
|
|
|
const login = useCallback(async (input: AdminLoginInput) => {
|
|
try {
|
|
setAdmin(await adminApiClient.login(input));
|
|
} catch (err) {
|
|
// Rethrown as-is — `LoginPage`'s submit handler catches and displays
|
|
// it; this callback just isn't allowed a bare `await`.
|
|
throw err;
|
|
}
|
|
}, []);
|
|
|
|
const logout = useCallback(async () => {
|
|
try {
|
|
await adminApiClient.logout();
|
|
setAdmin(null);
|
|
} catch (err) {
|
|
throw err; // see login()'s catch comment
|
|
}
|
|
}, []);
|
|
|
|
return (
|
|
<AdminAuthContext.Provider value={{ admin, isLoading, login, logout }}>
|
|
{children}
|
|
</AdminAuthContext.Provider>
|
|
);
|
|
}
|
|
|
|
/** Reads the current admin auth state/actions. Must be called within an {@link AdminAuthProvider}. */
|
|
export function useAdminAuth(): AdminAuthContextValue {
|
|
const ctx = useContext(AdminAuthContext);
|
|
if (!ctx) {
|
|
throw new Error("useAdminAuth must be used within an AdminAuthProvider");
|
|
}
|
|
return ctx;
|
|
}
|