Adds auth pages

This commit is contained in:
2026-06-21 00:15:28 +02:00
parent 7dfc3a9692
commit ab93a5c7d1
28 changed files with 2785 additions and 45 deletions
+85 -10
View File
@@ -7,13 +7,47 @@ import {
redirect,
} from '@tanstack/react-router';
import type { AuthContextValue } from '@/contexts/auth-context';
import type { SetupStatus } from '@/api/types';
import { api } from '@/lib/api-client';
import { AppLayout } from '@/components/layout/AppLayout';
import { LoginPage } from '@/pages/LoginPage';
import { RoleGuard } from '@/components/auth/RoleGuard';
export interface RouterContext {
auth: AuthContextValue;
}
// ---------------------------------------------------------------------------
// InitGuard: module-level session cache for setup status (BR-U2-08).
// One network request per page load; subsequent beforeLoad calls return cached
// data synchronously via Promise.resolve().
// ---------------------------------------------------------------------------
let _setupStatusCache: SetupStatus | null = null;
let _setupStatusPromise: Promise<SetupStatus> | null = null;
async function fetchSetupStatus(): Promise<SetupStatus> {
if (_setupStatusCache !== null) return _setupStatusCache;
if (_setupStatusPromise === null) {
_setupStatusPromise = api
.get<SetupStatus>('/Setup/status')
.then((s) => {
_setupStatusCache = s;
return s;
})
.catch((err: unknown) => {
_setupStatusPromise = null;
throw err;
});
}
return _setupStatusPromise;
}
// Exposed for tests so each test starts with a clean cache.
export function _resetSetupStatusCache(): void {
_setupStatusCache = null;
_setupStatusPromise = null;
}
function RouteFallback() {
return (
<div className="flex min-h-40 items-center justify-center text-muted-foreground">
@@ -22,10 +56,14 @@ function RouteFallback() {
);
}
/**
* Wrap a per-feature page in a lazy boundary so Vite emits a separate chunk
* (NFR-U1-01 / Q1-A). The auth/root shell and login stay eager for fast paint.
*/
function BootstrapSplash() {
return (
<div className="flex min-h-svh items-center justify-center text-muted-foreground">
<span className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
);
}
function lazyPage<P extends Record<string, never>>(
factory: () => Promise<{ [key: string]: ComponentType<P> }>,
exportName: string,
@@ -40,11 +78,33 @@ function lazyPage<P extends Record<string, never>>(
};
}
// ---------------------------------------------------------------------------
// Routes
// ---------------------------------------------------------------------------
const rootRoute = createRootRouteWithContext<RouterContext>()({
pendingComponent: BootstrapSplash,
pendingMs: 0,
beforeLoad: async ({ location }) => {
let status: SetupStatus;
try {
status = await fetchSetupStatus();
} catch {
// Network failure — let routes render; API calls will surface errors.
return;
}
const onSetup = location.pathname === '/setup';
if (!status.initialized && !onSetup) {
throw redirect({ to: '/setup' });
}
if (status.initialized && onSetup) {
throw redirect({ to: '/login' });
}
},
component: () => <Outlet />,
});
// '/' redirects into the protected area; the guard sends guests to /login.
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
@@ -59,7 +119,6 @@ const loginRoute = createRoute({
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
}),
// Authenticated users never see /login (BR-U1-06).
beforeLoad: ({ context }) => {
if (context.auth.isAuthenticated) {
throw redirect({ to: '/dashboard' });
@@ -74,7 +133,15 @@ const setupRoute = createRoute({
component: lazyPage(() => import('@/pages/SetupPage'), 'SetupPage'),
});
// Layout route guarding every protected page (BR-U1-05).
const inviteCompleteRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/invite/complete',
validateSearch: (search: Record<string, unknown>): { token?: string } => ({
token: typeof search.token === 'string' ? search.token : undefined,
}),
component: lazyPage(() => import('@/pages/InviteCompletePage'), 'InviteCompletePage'),
});
const authenticatedRoute = createRoute({
getParentRoute: () => rootRoute,
id: '_authenticated',
@@ -95,26 +162,34 @@ const dashboardRoute = createRoute({
const usersRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/users',
component: lazyPage(() => import('@/pages/UsersPage'), 'UsersPage'),
component: () => (
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
{lazyPage(() => import('@/pages/UsersPage'), 'UsersPage')()}
</RoleGuard>
),
});
const cmsRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/cms',
component: lazyPage(() => import('@/pages/CmsPage'), 'CmsPage'),
component: () => (
<RoleGuard allowedRoles={['Owner']}>
{lazyPage(() => import('@/pages/CmsPage'), 'CmsPage')()}
</RoleGuard>
),
});
export const routeTree = rootRoute.addChildren([
indexRoute,
loginRoute,
setupRoute,
inviteCompleteRoute,
authenticatedRoute.addChildren([dashboardRoute, usersRoute, cmsRoute]),
]);
export const router = createRouter({
routeTree,
defaultPreload: 'intent',
// Real auth is injected per render via RouterProvider's `context` prop.
context: { auth: undefined as unknown as AuthContextValue },
});