2025-10-14 22:04:37 -07:00
|
|
|
import { Form, redirect, useNavigate } from "react-router";
|
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
|
|
|
import { auth } from "~/lib/auth.server";
|
2025-10-14 22:04:37 -07:00
|
|
|
import type { Route } from "./+types/$teamId.settings";
|
2026-03-10 12:10:52 -07:00
|
|
|
|
2025-10-14 22:04:37 -07:00
|
|
|
import {
|
|
|
|
|
findTeamById,
|
|
|
|
|
updateTeam,
|
|
|
|
|
removeTeamOwner,
|
|
|
|
|
} from "~/models/team";
|
|
|
|
|
import { findSeasonById } from "~/models/season";
|
2026-05-06 14:47:37 -07:00
|
|
|
import { findUserById } from "~/models/user";
|
|
|
|
|
import { resolveUserAvatarData } from "~/lib/avatar-data";
|
2025-10-14 22:04:37 -07:00
|
|
|
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";
|
2026-05-06 14:47:37 -07:00
|
|
|
import { AvatarEditor } from "~/components/ui/AvatarEditor";
|
|
|
|
|
import { parseFlagConfig } from "~/lib/flag-types";
|
|
|
|
|
import { deleteCloudinaryImageByUrl } from "~/lib/cloudinary.server";
|
|
|
|
|
import { logger } from "~/lib/logger";
|
2025-10-14 22:04:37 -07:00
|
|
|
import {
|
|
|
|
|
AlertDialog,
|
|
|
|
|
AlertDialogAction,
|
|
|
|
|
AlertDialogCancel,
|
|
|
|
|
AlertDialogContent,
|
|
|
|
|
AlertDialogDescription,
|
|
|
|
|
AlertDialogFooter,
|
|
|
|
|
AlertDialogHeader,
|
|
|
|
|
AlertDialogTitle,
|
|
|
|
|
AlertDialogTrigger,
|
|
|
|
|
} from "~/components/ui/alert-dialog";
|
2026-05-04 20:31:44 -07:00
|
|
|
import { syncPrivateBracktParticipants } from "~/services/brackt.server";
|
2025-10-14 22:04:37 -07:00
|
|
|
|
2026-03-10 12:10:52 -07:00
|
|
|
export function meta({ data }: Route.MetaArgs): Route.MetaDescriptors {
|
|
|
|
|
return [{ title: `Team Settings — ${data?.team?.name ?? "Team"} - Brackt` }];
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-14 22:04:37 -07:00
|
|
|
export async function loader(args: Route.LoaderArgs) {
|
|
|
|
|
const { params } = args;
|
|
|
|
|
const { teamId } = params;
|
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
|
|
|
const session = await auth.api.getSession({ headers: args.request.headers });
|
|
|
|
|
const userId = session?.user.id ?? null;
|
2025-10-14 22:04:37 -07:00
|
|
|
|
|
|
|
|
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 });
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-06 14:47:37 -07:00
|
|
|
const owner = await findUserById(userId);
|
|
|
|
|
const ownerAvatarData = owner ? resolveUserAvatarData(owner) : null;
|
|
|
|
|
|
|
|
|
|
return { team, season, ownerAvatarData };
|
2025-10-14 22:04:37 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function action(args: Route.ActionArgs) {
|
|
|
|
|
const { params, request } = args;
|
|
|
|
|
const { teamId } = params;
|
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
|
|
|
const session = await auth.api.getSession({ headers: args.request.headers });
|
|
|
|
|
const userId = session?.user.id ?? null;
|
2025-10-14 22:04:37 -07:00
|
|
|
|
|
|
|
|
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");
|
|
|
|
|
|
2026-05-06 14:47:37 -07:00
|
|
|
if (intent === "update-avatar-flag") {
|
|
|
|
|
const rawConfig = formData.get("flagConfig");
|
|
|
|
|
if (typeof rawConfig !== "string") {
|
|
|
|
|
return { error: "Flag config is required" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let parsedConfig: unknown;
|
|
|
|
|
try {
|
|
|
|
|
parsedConfig = JSON.parse(rawConfig);
|
|
|
|
|
} catch {
|
|
|
|
|
return { error: "Invalid flag config" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const flagConfig = parseFlagConfig(parsedConfig);
|
|
|
|
|
if (!flagConfig) {
|
|
|
|
|
return { error: "Invalid flag config" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await updateTeam(teamId, {
|
|
|
|
|
flagConfig,
|
|
|
|
|
avatarType: "flag",
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { success: true };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (intent === "remove-avatar-photo") {
|
|
|
|
|
await updateTeam(teamId, {
|
|
|
|
|
logoUrl: null,
|
|
|
|
|
avatarType: "owner",
|
|
|
|
|
});
|
|
|
|
|
if (team.logoUrl) {
|
|
|
|
|
deleteCloudinaryImageByUrl(team.logoUrl).catch((error) => {
|
|
|
|
|
logger.error("Failed to delete team avatar from Cloudinary:", error);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { success: true };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (intent === "use-owner-avatar") {
|
|
|
|
|
await updateTeam(teamId, { avatarType: "owner", flagConfig: null });
|
|
|
|
|
if (team.avatarType === "uploaded" && team.logoUrl) {
|
|
|
|
|
deleteCloudinaryImageByUrl(team.logoUrl).catch((error) => {
|
|
|
|
|
logger.error("Failed to delete replaced team avatar from Cloudinary:", error);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
return { success: true };
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-14 22:04:37 -07:00
|
|
|
if (intent === "update") {
|
|
|
|
|
const name = formData.get("name");
|
|
|
|
|
|
|
|
|
|
if (!name || typeof name !== "string") {
|
|
|
|
|
return { error: "Team name is required" };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await updateTeam(teamId, {
|
|
|
|
|
name: name.trim(),
|
|
|
|
|
});
|
2026-05-04 20:31:44 -07:00
|
|
|
await syncPrivateBracktParticipants(team.seasonId);
|
2025-10-14 22:04:37 -07:00
|
|
|
|
|
|
|
|
const season = await findSeasonById(team.seasonId);
|
|
|
|
|
return redirect(`/leagues/${season?.leagueId}?updated=true`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (intent === "leave") {
|
|
|
|
|
await removeTeamOwner(teamId);
|
2025-10-14 22:45:24 -07:00
|
|
|
return redirect("/?left=true");
|
2025-10-14 22:04:37 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { error: "Invalid action" };
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-06 14:47:37 -07:00
|
|
|
export default function TeamSettings({ loaderData, actionData }: Route.ComponentProps) {
|
2025-10-14 22:04:37 -07:00
|
|
|
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">
|
2026-05-06 14:47:37 -07:00
|
|
|
{actionData && "success" in actionData && actionData.success && (
|
|
|
|
|
<p className="text-sm text-[#adf661]">Team settings updated.</p>
|
|
|
|
|
)}
|
|
|
|
|
{actionData && "error" in actionData && actionData.error && (
|
|
|
|
|
<p className="text-sm text-destructive">{actionData.error}</p>
|
|
|
|
|
)}
|
|
|
|
|
|
|
|
|
|
<Card>
|
|
|
|
|
<CardHeader>
|
|
|
|
|
<CardTitle>Team Avatar</CardTitle>
|
|
|
|
|
<CardDescription>
|
|
|
|
|
Update the flag or submit a photo for review
|
|
|
|
|
</CardDescription>
|
|
|
|
|
</CardHeader>
|
|
|
|
|
<CardContent>
|
|
|
|
|
<AvatarEditor
|
|
|
|
|
id={team.id}
|
|
|
|
|
isTeam
|
|
|
|
|
currentAvatarType={team.avatarType}
|
|
|
|
|
flagConfig={team.flagConfig}
|
|
|
|
|
uploadedPhotoUrl={team.avatarType === "uploaded" ? team.logoUrl : null}
|
|
|
|
|
uploadUrl="/api/upload-team-logo"
|
|
|
|
|
ownerAvatarData={loaderData.ownerAvatarData}
|
|
|
|
|
/>
|
|
|
|
|
</CardContent>
|
|
|
|
|
</Card>
|
|
|
|
|
|
2025-10-14 22:04:37 -07:00
|
|
|
<Card>
|
|
|
|
|
<CardHeader>
|
|
|
|
|
<CardTitle>Team Information</CardTitle>
|
|
|
|
|
<CardDescription>
|
2026-05-06 14:47:37 -07:00
|
|
|
Update your team name
|
2025-10-14 22:04:37 -07:00
|
|
|
</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>
|
|
|
|
|
|
|
|
|
|
<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>
|
|
|
|
|
);
|
|
|
|
|
}
|