Follow-up to PR #406 — addresses the two items deferred from the audit: #7 — Centralize auth helpers - New `requireSessionUser(request)` in lib/auth/session.server.ts that returns the user or throws a redirect to /auth/login. - New `requireSessionUserJson(request)` companion that throws a 401 JSON response (for fetcher/JSON endpoints). - Replace the repeated const user = await getSessionUser(request); if (!user) return redirect("/auth/login"); pattern across 18 route loaders/actions. Removes the duplicated guard preamble and gives a single chokepoint to evolve later (e.g., for terms-version gating). #8 — Extract heavy loaders into .server.ts siblings - routes/home.tsx → home.server.ts (DB count query + listActivities + listRecentPublicActivities) - routes/users.$username.tsx → users.$username.server.ts (user lookup + follow state + counts + listPublicRoutes/Activities + persona check) - routes/settings.connections.tsx → settings.connections.server.ts (connected_services join + manifest merge) Each route file shrinks to a thin delegator: `loader` calls `loadXxx(request)`. The component module no longer transitively pulls `getDb` and Drizzle schema into its import graph — Vite's tree-shake already strips server-only code from the client bundle, but the explicit `.server.ts` suffix makes that contract local and auditable. Other 17 routes that mix loader/action with components are left as-is for now: they're each small enough that the split adds churn without buying much clarity. The pattern is documented by the three examples; the rest can convert opportunistically when they grow. Tests: - lib/auth/session.server.test.ts (4 cases — redirect for missing cookie, redirect for ghost userId, success path, JSON 401 variant) Full repo: pnpm typecheck, pnpm lint, pnpm test all green (181 passed | 31 integration-gated skipped). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
92 lines
2.9 KiB
TypeScript
92 lines
2.9 KiB
TypeScript
// Server-only data loader for the home route. Lives separately from
|
|
// `home.tsx` so the component file imports nothing that pulls in the DB
|
|
// client or other server-side modules at module-evaluation time. The
|
|
// route's `loader` is a thin delegator.
|
|
|
|
import { eq, count } from "drizzle-orm";
|
|
import { getSessionUser } from "~/lib/auth/session.server";
|
|
import { getDb } from "~/lib/db";
|
|
import { credentials } from "@trails-cool/db/schema/journal";
|
|
import { listActivities, listRecentPublicActivities } from "~/lib/activities.server";
|
|
|
|
export interface HomeActivityCard {
|
|
id: string;
|
|
name: string;
|
|
distance: number | null;
|
|
elevationGain: number | null;
|
|
duration: number | null;
|
|
startedAt: string | null;
|
|
createdAt: string;
|
|
geojson: string | null;
|
|
// Populated only for the public (logged-out) feed, where the card
|
|
// needs to attribute the activity to an owner. Personal feed skips
|
|
// these because it's always "you".
|
|
ownerUsername: string | null;
|
|
ownerDisplayName: string | null;
|
|
}
|
|
|
|
export interface HomeLoaderData {
|
|
user: { id: string; username: string; displayName: string | null } | null;
|
|
showAddPasskey: boolean;
|
|
plannerUrl: string;
|
|
isFlagship: boolean;
|
|
activities: HomeActivityCard[];
|
|
}
|
|
|
|
export async function loadHomeData(request: Request): Promise<HomeLoaderData> {
|
|
const user = await getSessionUser(request);
|
|
const url = new URL(request.url);
|
|
const addPasskeyParam = url.searchParams.get("add-passkey") === "1" && user !== null;
|
|
|
|
let showAddPasskey = false;
|
|
if (addPasskeyParam && user) {
|
|
const db = getDb();
|
|
const [row] = await db
|
|
.select({ count: count() })
|
|
.from(credentials)
|
|
.where(eq(credentials.userId, user.id));
|
|
showAddPasskey = (row?.count ?? 0) === 0;
|
|
}
|
|
|
|
const plannerUrl = process.env.PLANNER_URL ?? "https://planner.trails.cool";
|
|
const isFlagship = process.env.IS_FLAGSHIP === "true";
|
|
|
|
let activities: HomeActivityCard[];
|
|
if (user) {
|
|
const rows = await listActivities(user.id);
|
|
activities = rows.slice(0, 20).map((a) => ({
|
|
id: a.id,
|
|
name: a.name,
|
|
distance: a.distance,
|
|
elevationGain: a.elevationGain,
|
|
duration: a.duration,
|
|
startedAt: a.startedAt?.toISOString() ?? null,
|
|
createdAt: a.createdAt.toISOString(),
|
|
geojson: a.geojson ?? null,
|
|
ownerUsername: null,
|
|
ownerDisplayName: null,
|
|
}));
|
|
} else {
|
|
const rows = await listRecentPublicActivities(20);
|
|
activities = rows.map((a) => ({
|
|
id: a.id,
|
|
name: a.name,
|
|
distance: a.distance,
|
|
elevationGain: a.elevationGain,
|
|
duration: a.duration,
|
|
startedAt: a.startedAt?.toISOString() ?? null,
|
|
createdAt: a.createdAt.toISOString(),
|
|
geojson: a.geojson ?? null,
|
|
ownerUsername: a.ownerUsername,
|
|
ownerDisplayName: a.ownerDisplayName,
|
|
}));
|
|
}
|
|
|
|
return {
|
|
user: user ? { id: user.id, username: user.username, displayName: user.displayName } : null,
|
|
showAddPasskey,
|
|
plannerUrl,
|
|
isFlagship,
|
|
activities,
|
|
};
|
|
}
|