UI: scaffold the web app - shell, themes, i18n, auth plumbing
React 19 + TypeScript + Vite + TanStack Query/Router in web/, built on the dev machine and shipped as static files (SPEC section 6). Typechecks and builds clean; the System page reads live /health through the Vite proxy, which proves browser -> proxy -> FastAPI -> PostgreSQL end to end. Themes: light, dark and blue (dark navy), as design tokens on data-theme. An inline script applies the stored theme before first paint. No colour literal lives outside tokens.css. check-contrast.mjs asserts WCAG AA for every text/background pair in every theme, with no dependencies. It failed on its first run and found three --border-strong values below the 3:1 that WCAG 1.4.11 wants for interactive boundaries; all three are fixed and 36 pairs now pass. Colour contrast is the classic silently-regressing property, so it gets a test rather than a promise. i18n is hand-written and typed rather than react-i18next: en.ts defines the key set, de.ts is typed against it, so a missing German string fails the build instead of quietly showing English to a German user. Authentication is built but NOT enforced, deliberately. /auth/session, /auth/login and /auth/logout do not exist yet, so router.tsx does not wrap routes in RequireAuth and a banner says so plainly. There is no development bypass: a bypass that works is the kind of code that survives into production, and an auth bypass that works is the worst possible bug. Gallery and Devices render honest empty states rather than mock rows. Fake data hides the layout problems real data exposes. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
5a098e44d8
commit
384b09371a
28 files changed
+3968
-1
No files matched your search
@@ -0,0 +1,122 @@
|
||||
/* The authentication shell.
|
||||
*
|
||||
* IMPORTANT, and deliberate: none of the endpoints this talks to exist yet.
|
||||
* Phase 3 builds /auth/session, /auth/login and /auth/logout on the server.
|
||||
* Until then `useAuth()` reports "anonymous" and <RequireAuth> is written but
|
||||
* NOT wired into the router -- see router.tsx.
|
||||
*
|
||||
* There is no development bypass here on purpose. A bypass is the kind of
|
||||
* code that survives into production because it works, and an auth bypass
|
||||
* that works is the worst possible bug. The app is simply ungated until the
|
||||
* real thing lands, which is visible and hard to forget.
|
||||
*
|
||||
* TOTP is part of the shape from the start (TODO 3.0): optional per user,
|
||||
* enforced for admins. Retrofitting it later would mean reopening the login
|
||||
* flow, the session model, the user model and the audit log at once.
|
||||
*/
|
||||
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { createContext, useCallback, useContext, useMemo } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { ApiError, apiGet, apiPost } from "../lib/api";
|
||||
|
||||
export type Role = "admin" | "editor" | "viewer";
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
role: Role;
|
||||
locale: string;
|
||||
theme: string;
|
||||
}
|
||||
|
||||
export interface Credentials {
|
||||
username: string;
|
||||
password: string;
|
||||
/** Six digits, when the account has TOTP enabled. */
|
||||
totp?: string;
|
||||
}
|
||||
|
||||
export type AuthState =
|
||||
| { status: "loading" }
|
||||
/** The server has no auth endpoints yet. Distinct from "signed out". */
|
||||
| { status: "unavailable" }
|
||||
| { status: "anonymous" }
|
||||
| { status: "authenticated"; user: User };
|
||||
|
||||
interface AuthValue {
|
||||
state: AuthState;
|
||||
signIn: (credentials: Credentials) => Promise<void>;
|
||||
signOut: () => Promise<void>;
|
||||
/** Convenience for `state.status === "authenticated" && role check`. */
|
||||
can: (...roles: Role[]) => boolean;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthValue | null>(null);
|
||||
|
||||
function useSessionQuery() {
|
||||
return useQuery<User | null, ApiError>({
|
||||
queryKey: ["auth", "session"],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
return await apiGet<User>("/auth/session");
|
||||
} catch (error) {
|
||||
// 401 is the normal "not signed in" answer, not a failure.
|
||||
if (error instanceof ApiError && error.status === 401) return null;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
retry: false,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const queryClient = useQueryClient();
|
||||
const query = useSessionQuery();
|
||||
|
||||
const state = useMemo<AuthState>(() => {
|
||||
if (query.isPending) return { status: "loading" };
|
||||
if (query.error?.isMissingEndpoint) return { status: "unavailable" };
|
||||
if (query.data) return { status: "authenticated", user: query.data };
|
||||
return { status: "anonymous" };
|
||||
}, [query.isPending, query.error, query.data]);
|
||||
|
||||
const signIn = useCallback(
|
||||
async (credentials: Credentials) => {
|
||||
const user = await apiPost<User>("/auth/login", credentials);
|
||||
queryClient.setQueryData(["auth", "session"], user);
|
||||
},
|
||||
[queryClient]
|
||||
);
|
||||
|
||||
const signOut = useCallback(async () => {
|
||||
await apiPost("/auth/logout");
|
||||
queryClient.setQueryData(["auth", "session"], null);
|
||||
// Anything cached under the old identity must not be shown to the next one.
|
||||
await queryClient.invalidateQueries();
|
||||
}, [queryClient]);
|
||||
|
||||
const can = useCallback(
|
||||
(...roles: Role[]) => state.status === "authenticated" && roles.includes(state.user.role),
|
||||
[state]
|
||||
);
|
||||
|
||||
const value = useMemo<AuthValue>(() => ({ state, signIn, signOut, can }), [
|
||||
state,
|
||||
signIn,
|
||||
signOut,
|
||||
can,
|
||||
]);
|
||||
|
||||
return <AuthContext value={value}>{children}</AuthContext>;
|
||||
}
|
||||
|
||||
export function useAuth(): AuthValue {
|
||||
const value = useContext(AuthContext);
|
||||
if (value === null) {
|
||||
throw new Error("useAuth must be used inside <AuthProvider>");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useState } from "react";
|
||||
import type { FormEvent } from "react";
|
||||
|
||||
import { useT } from "../i18n/I18nProvider";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { useAuth } from "./AuthProvider";
|
||||
|
||||
/* The sign-in form. Fully built, and currently talking to an endpoint that
|
||||
* does not exist -- a 404 is reported honestly rather than dressed up as
|
||||
* "wrong password". The TOTP field is present from the start because the
|
||||
* policy is decided (TODO 3.0). */
|
||||
export function LoginPage() {
|
||||
const t = useT();
|
||||
const { signIn } = useAuth();
|
||||
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [totp, setTotp] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function onSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await signIn({ username, password, totp: totp || undefined });
|
||||
} catch (cause) {
|
||||
if (cause instanceof ApiError && cause.isMissingEndpoint) {
|
||||
setError(t("auth.unavailable"));
|
||||
} else {
|
||||
setError(t("auth.failed"));
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="centered-page">
|
||||
<form className="card login-card" onSubmit={onSubmit}>
|
||||
<h1 className="login-title">{t("auth.signIn")}</h1>
|
||||
|
||||
<label className="field">
|
||||
<span className="field-label">{t("auth.username")}</span>
|
||||
<input
|
||||
className="input"
|
||||
autoComplete="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span className="field-label">{t("auth.password")}</span>
|
||||
<input
|
||||
className="input"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span className="field-label">{t("auth.totp")}</span>
|
||||
<input
|
||||
className="input"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9]{6}"
|
||||
maxLength={6}
|
||||
value={totp}
|
||||
onChange={(e) => setTotp(e.target.value)}
|
||||
/>
|
||||
<span className="field-hint">{t("auth.totpHint")}</span>
|
||||
</label>
|
||||
|
||||
{error !== null && (
|
||||
<p className="alert alert-danger" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button className="button button-primary" type="submit" disabled={busy}>
|
||||
{busy ? t("auth.signingIn") : t("auth.signIn")}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { useT } from "../i18n/I18nProvider";
|
||||
import { LoginPage } from "./LoginPage";
|
||||
import { useAuth } from "./AuthProvider";
|
||||
import type { Role } from "./AuthProvider";
|
||||
|
||||
/* Route guard. Written now, wired in when Phase 3 lands the endpoints --
|
||||
* see router.tsx for why it is not used yet.
|
||||
*
|
||||
* This is the client-side half only. It decides what to *render*; it is not
|
||||
* access control. The server authorises every request independently, and the
|
||||
* image bytes go through the auth-checked handoff (SPEC 3.3), because an
|
||||
* unguessable URL is not access control either. */
|
||||
export function RequireAuth({
|
||||
children,
|
||||
roles,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
/** When given, the signed-in user must hold one of these roles. */
|
||||
roles?: Role[];
|
||||
}) {
|
||||
const t = useT();
|
||||
const { state, can } = useAuth();
|
||||
|
||||
if (state.status === "loading") {
|
||||
return <p className="muted centered-page">{t("common.loading")}</p>;
|
||||
}
|
||||
|
||||
if (state.status === "unavailable" || state.status === "anonymous") {
|
||||
return <LoginPage />;
|
||||
}
|
||||
|
||||
if (roles !== undefined && !can(...roles)) {
|
||||
return (
|
||||
<div className="centered-page">
|
||||
<p className="alert alert-danger">{t("common.error")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
Reference in new issue
Block a user