trails/apps/journal/app/routes/users.$username.server.ts
Ullrich Schäfer 8eba5b2d9e
fix(journal): centralize session-auth helpers + extract .server.ts siblings
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>
2026-05-24 10:44:33 +02:00

97 lines
3.3 KiB
TypeScript

// Server-only loader for the user profile page. Splitting this out keeps
// the route component file free of direct DB/auth/follow imports — see
// `home.server.ts` for the pattern.
import { data } from "react-router";
import { eq } from "drizzle-orm";
import { getDb } from "~/lib/db";
import { users } from "@trails-cool/db/schema/journal";
import { getSessionUser } from "~/lib/auth/session.server";
import { listPublicRoutesForOwner } from "~/lib/routes.server";
import { listPublicActivitiesForOwner } from "~/lib/activities.server";
import { loadPersona } from "~/lib/demo-bot.server";
import { countFollowers, countFollowing, getFollowState } from "~/lib/follow.server";
export async function loadUserProfile(request: Request, username: string) {
const db = getDb();
const [user] = await db.select().from(users).where(eq(users.username, username));
if (!user) {
throw data({ error: "User not found" }, { status: 404 });
}
const currentUser = await getSessionUser(request);
const isOwn = currentUser?.id === user.id;
// Follow state: null when anonymous or owner; { following, pending }
// otherwise.
const followState = !isOwn && currentUser
? await getFollowState(currentUser.id, user.username)
: null;
// Locked-account model: a private profile renders a stub for
// non-followers (anonymous OR signed-in but not an accepted follower).
// Owners always see their own profile in full.
const canSeeContent =
isOwn ||
user.profileVisibility === "public" ||
(followState !== null && followState.following === true);
// For private-stub viewers we still want counts (cheap) but skip the
// expensive content fetches.
const [followers, following] = await Promise.all([
countFollowers(user.id),
countFollowing(user.id),
]);
const url = new URL(request.url);
const sortParam = url.searchParams.get("sort");
const activitySort = sortParam === "addedAt" ? "addedAt" : "startedAt";
const [publicRoutes, publicActivities] = canSeeContent
? await Promise.all([
listPublicRoutesForOwner(user.id),
listPublicActivitiesForOwner(user.id, activitySort),
])
: [[], []];
// Demo-account badge: true when this profile matches the instance's
// configured demo persona username. Computed server-side so we don't
// ship the persona config through client HTML.
const isDemoUser = user.username === loadPersona().username;
return {
user: {
username: user.username,
displayName: user.displayName,
bio: user.bio,
domain: user.domain,
createdAt: user.createdAt.toISOString(),
},
routes: publicRoutes.map((r) => ({
id: r.id,
name: r.name,
description: r.description,
distance: r.distance,
elevationGain: r.elevationGain,
updatedAt: r.updatedAt.toISOString(),
})),
activities: publicActivities.map((a) => ({
id: a.id,
name: a.name,
description: a.description,
distance: a.distance,
duration: a.duration,
startedAt: a.startedAt?.toISOString() ?? null,
createdAt: a.createdAt.toISOString(),
})),
activitySort,
isOwn,
isDemoUser,
followers,
following,
followState,
isLoggedIn: currentUser !== null,
profileVisibility: user.profileVisibility,
canSeeContent,
};
}