* 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>
126 lines
4.2 KiB
TypeScript
126 lines
4.2 KiB
TypeScript
import { auth } from "~/lib/auth.server";
|
|
import { addDays, subDays } from "date-fns";
|
|
import { ArrowLeft } from "lucide-react";
|
|
import { Link } from "react-router";
|
|
|
|
import type { Route } from "./+types/$leagueId.upcoming-events";
|
|
import {
|
|
findLeagueById,
|
|
isCommissioner,
|
|
isUserLeagueMember,
|
|
} from "~/models";
|
|
import { findCurrentSeasonWithSports } from "~/models/season";
|
|
import { findTeamByOwnerAndSeason } from "~/models/team";
|
|
import { getDraftedParticipantsBySportsSeason } from "~/models/draft-pick";
|
|
import { getUpcomingEventsForDraftedParticipants } from "~/models/scoring-event";
|
|
import type { CalendarPanelEvent } from "~/components/sport-season/UpcomingCalendarPanel";
|
|
import { UpcomingCalendarPanel } from "~/components/sport-season/UpcomingCalendarPanel";
|
|
import { toEventSortKey } from "~/lib/date-utils";
|
|
|
|
export function meta({ data }: Route.MetaArgs) {
|
|
const leagueName = data?.leagueName ?? "League";
|
|
return [{ title: `${leagueName} — Upcoming Events — Brackt` }];
|
|
}
|
|
|
|
export async function loader(args: Route.LoaderArgs) {
|
|
const session = await auth.api.getSession({ headers: args.request.headers });
|
|
const userId = session?.user.id ?? null;
|
|
const { leagueId } = args.params;
|
|
|
|
const league = await findLeagueById(leagueId);
|
|
if (!league) {
|
|
throw new Response("League not found", { status: 404 });
|
|
}
|
|
|
|
if (!userId) {
|
|
throw new Response("You must be logged in to view this league", { status: 401 });
|
|
}
|
|
|
|
const [isUserCommissioner, isUserMember] = await Promise.all([
|
|
isCommissioner(leagueId, userId),
|
|
isUserLeagueMember(leagueId, userId),
|
|
]);
|
|
|
|
if (!isUserCommissioner && !isUserMember) {
|
|
throw new Response("You do not have access to this league", { status: 403 });
|
|
}
|
|
|
|
const seasonWithSports = await findCurrentSeasonWithSports(leagueId);
|
|
|
|
const today = new Date();
|
|
const dateFromStr = subDays(today, 1).toISOString().split("T")[0];
|
|
const dateToStr = addDays(today, 60).toISOString().split("T")[0];
|
|
|
|
const calendarEvents: CalendarPanelEvent[] = [];
|
|
|
|
if (seasonWithSports?.seasonSports && seasonWithSports.id) {
|
|
const myTeam = await findTeamByOwnerAndSeason(userId, seasonWithSports.id);
|
|
|
|
if (myTeam) {
|
|
const participantsBySportsSeason = await getDraftedParticipantsBySportsSeason(
|
|
myTeam.id,
|
|
seasonWithSports.id
|
|
);
|
|
|
|
const perSeasonEvents = await Promise.all(
|
|
seasonWithSports.seasonSports.map(async ({ sportsSeason: ss }) => {
|
|
const draftedParticipants = participantsBySportsSeason.get(ss.id) ?? [];
|
|
if (draftedParticipants.length === 0) return [];
|
|
|
|
const events = await getUpcomingEventsForDraftedParticipants(
|
|
ss.id,
|
|
ss.scoringPattern ?? "",
|
|
draftedParticipants,
|
|
dateFromStr,
|
|
dateToStr
|
|
);
|
|
|
|
return events.map((event) => ({
|
|
...event,
|
|
sportName: ss.sport.name,
|
|
sportSeasonName: ss.name,
|
|
sportsSeasonPageUrl: `/leagues/${leagueId}/sports-seasons/${ss.id}`,
|
|
}));
|
|
})
|
|
);
|
|
|
|
calendarEvents.push(...perSeasonEvents.flat());
|
|
}
|
|
}
|
|
|
|
const upcomingCalendarEvents = calendarEvents.toSorted((a, b) =>
|
|
toEventSortKey(a).localeCompare(toEventSortKey(b))
|
|
);
|
|
|
|
return {
|
|
leagueName: league.name,
|
|
leagueId,
|
|
upcomingCalendarEvents,
|
|
};
|
|
}
|
|
|
|
export default function LeagueUpcomingEventsPage({ loaderData }: Route.ComponentProps) {
|
|
const { leagueName, leagueId, upcomingCalendarEvents } = loaderData;
|
|
|
|
return (
|
|
<div className="container mx-auto py-8 px-4 max-w-2xl">
|
|
<div className="mb-6">
|
|
<Link
|
|
to={`/leagues/${leagueId}`}
|
|
className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors mb-4"
|
|
>
|
|
<ArrowLeft className="h-3.5 w-3.5" />
|
|
{leagueName}
|
|
</Link>
|
|
<h1 className="text-3xl font-bold">Upcoming Events</h1>
|
|
<p className="text-muted-foreground mt-1">Next 60 days · {leagueName}</p>
|
|
</div>
|
|
|
|
<UpcomingCalendarPanel
|
|
events={upcomingCalendarEvents}
|
|
showLeague={false}
|
|
emptyMessage="No upcoming events in the next 60 days for this league."
|
|
/>
|
|
</div>
|
|
);
|
|
}
|