brackt/app/routes/teams/$teamId.settings.tsx
Chris Parsons ba9bf64e37
Migrate authentication from Clerk to BetterAuth (#324)
* Migrate authentication from Clerk to BetterAuth (#322)

Replaces @clerk/react-router with self-hosted better-auth to eliminate
the external Clerk dependency and keep all user/session data in our own
PostgreSQL database.

**What changed**
- New: auth.server.ts (BetterAuth config w/ Drizzle adapter, bcrypt, Resend), auth-client.ts, api.auth.$.ts handler
- New: /login and /register pages with email+password and Google/Discord OAuth; open-redirect guard on redirectTo param
- New: UserMenu component replacing Clerk's UserButton
- Schema: sessions, accounts, verifications tables; emailVerified column; clerkId made nullable
- Migrations 0081 (BetterAuth tables) and 0082 (accounts extra columns for v1.6.9)
- All ~30 route files: getAuth → auth.api.getSession, isUserAdminByClerkId → isUserAdmin
- root.tsx: isAdmin read directly from session.user.isAdmin (no extra DB query)
- useDraftAuthRecovery: removed Clerk JWT refresh logic; replaced with cookie-session check
- models/user.ts: removed findUserByClerkId, findOrCreateUser, updateUserByClerkId (webhook pattern)
- Deleted: app/routes/api/webhooks/clerk.ts; uninstalled @clerk/react-router, @clerk/themes, svix
- scripts/migrate.mjs: extended with idempotent Clerk → BetterAuth data migration (FK conversion, email_verified, OAuth accounts)
- scripts/migrate-clerk-passwords.mjs: one-time script to import bcrypt hashes from Clerk CSV export
- BETTERAUTH_MIGRATION.md: dev and production runbooks
- All test mocks updated: vi.mock('~/lib/auth.server') instead of @clerk/react-router/server
- Test fixtures: added emailVerified field

**Follow-up (post-stable)**
- Rename actor_clerk_id column → actor_user_id in commissioner_audit_log
- Drop clerk_id column from users once migration confirmed

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add .npmrc with legacy-peer-deps for better-auth/drizzle peer dep conflict

better-auth@1.6.9 declares peerOptional deps on drizzle-orm ^0.45.2 and
drizzle-kit >=0.31.4, but we run drizzle-orm ~0.36.3 / drizzle-kit ~0.28.1.
The adapter works correctly at runtime with our versions — the peer dep is
only for stricter type checking. This unblocks npm ci in CI without a risky
drizzle major-version upgrade.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:00:49 -07:00

219 lines
6.8 KiB
TypeScript

import { Form, redirect, useNavigate } from "react-router";
import { auth } from "~/lib/auth.server";
import type { Route } from "./+types/$teamId.settings";
import {
findTeamById,
updateTeam,
removeTeamOwner,
} from "~/models/team";
import { findSeasonById } from "~/models/season";
import { Button } from "~/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "~/components/ui/alert-dialog";
export function meta({ data }: Route.MetaArgs): Route.MetaDescriptors {
return [{ title: `Team Settings — ${data?.team?.name ?? "Team"} - Brackt` }];
}
export async function loader(args: Route.LoaderArgs) {
const { params } = args;
const { teamId } = params;
const session = await auth.api.getSession({ headers: args.request.headers });
const userId = session?.user.id ?? null;
if (!userId) {
throw new Response("You must be logged in", { status: 401 });
}
const team = await findTeamById(teamId);
if (!team) {
throw new Response("Team not found", { status: 404 });
}
// Only the team owner can access settings
if (team.ownerId !== userId) {
throw new Response("You do not have access to this team", { status: 403 });
}
const season = await findSeasonById(team.seasonId);
if (!season) {
throw new Response("Season not found", { status: 404 });
}
return { team, season };
}
export async function action(args: Route.ActionArgs) {
const { params, request } = args;
const { teamId } = params;
const session = await auth.api.getSession({ headers: args.request.headers });
const userId = session?.user.id ?? null;
if (!userId) {
throw new Response("You must be logged in", { status: 401 });
}
const team = await findTeamById(teamId);
if (!team) {
throw new Response("Team not found", { status: 404 });
}
// Only the team owner can modify settings
if (team.ownerId !== userId) {
throw new Response("You do not have access to this team", { status: 403 });
}
const formData = await request.formData();
const intent = formData.get("intent");
if (intent === "update") {
const name = formData.get("name");
const logoUrl = formData.get("logoUrl");
if (!name || typeof name !== "string") {
return { error: "Team name is required" };
}
await updateTeam(teamId, {
name: name.trim(),
logoUrl: logoUrl && typeof logoUrl === "string" ? logoUrl.trim() : undefined,
});
const season = await findSeasonById(team.seasonId);
return redirect(`/leagues/${season?.leagueId}?updated=true`);
}
if (intent === "leave") {
await removeTeamOwner(teamId);
return redirect("/?left=true");
}
return { error: "Invalid action" };
}
export default function TeamSettings({ loaderData }: Route.ComponentProps) {
const { team, season } = loaderData;
const navigate = useNavigate();
return (
<div className="container mx-auto py-8 px-4">
<div className="max-w-2xl mx-auto">
<div className="mb-8">
<div className="flex items-center justify-between mb-2">
<h1 className="text-4xl font-bold">Team Settings</h1>
<Button
variant="outline"
onClick={() => navigate(`/leagues/${season.leagueId}`)}
>
Back to League
</Button>
</div>
<p className="text-muted-foreground">
Manage your team settings and preferences
</p>
</div>
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Team Information</CardTitle>
<CardDescription>
Update your team name and logo
</CardDescription>
</CardHeader>
<CardContent>
<Form method="post" className="space-y-4">
<input type="hidden" name="intent" value="update" />
<div className="space-y-2">
<Label htmlFor="name">Team Name</Label>
<Input
id="name"
name="name"
type="text"
defaultValue={team.name}
required
maxLength={255}
/>
</div>
<div className="space-y-2">
<Label htmlFor="logoUrl">Team Logo URL (optional)</Label>
<Input
id="logoUrl"
name="logoUrl"
type="url"
defaultValue={team.logoUrl || ""}
placeholder="https://example.com/logo.png"
maxLength={512}
/>
<p className="text-xs text-muted-foreground">
Enter a URL to an image for your team logo
</p>
</div>
<Button type="submit">Save Changes</Button>
</Form>
</CardContent>
</Card>
<Card className="border-destructive">
<CardHeader>
<CardTitle className="text-destructive">Danger Zone</CardTitle>
<CardDescription>
Irreversible actions for your team
</CardDescription>
</CardHeader>
<CardContent>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="destructive">Leave League</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you sure?</AlertDialogTitle>
<AlertDialogDescription>
This will remove you as the owner of "{team.name}" and make the team
available for others to claim. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<Form method="post">
<input type="hidden" name="intent" value="leave" />
<AlertDialogAction type="submit" className="bg-destructive hover:bg-destructive/90">
Leave League
</AlertDialogAction>
</Form>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</CardContent>
</Card>
</div>
</div>
</div>
);
}