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>
87 lines
2.6 KiB
TypeScript
87 lines
2.6 KiB
TypeScript
import { eq, desc, and, inArray, sql } from "drizzle-orm";
|
|
import { database } from "~/database/context";
|
|
import * as schema from "~/database/schema";
|
|
import { findUserById, getUserDisplayName } from "~/models/user";
|
|
|
|
export type AuditLogEntry = typeof schema.commissionerAuditLog.$inferSelect;
|
|
export type NewAuditLogEntry = typeof schema.commissionerAuditLog.$inferInsert;
|
|
export type AuditAction = typeof schema.auditActionEnum.enumValues[number];
|
|
|
|
export interface AuditLogPage {
|
|
entries: AuditLogEntry[];
|
|
total: number;
|
|
hasMore: boolean;
|
|
}
|
|
|
|
export async function createAuditLogEntry(
|
|
data: NewAuditLogEntry
|
|
): Promise<AuditLogEntry> {
|
|
const db = database();
|
|
const [entry] = await db
|
|
.insert(schema.commissionerAuditLog)
|
|
.values(data)
|
|
.returning();
|
|
return entry;
|
|
}
|
|
|
|
export async function getAuditLogForSeason(
|
|
seasonId: string,
|
|
options?: { limit?: number; offset?: number; actions?: AuditAction[] }
|
|
): Promise<AuditLogPage> {
|
|
const db = database();
|
|
const limit = options?.limit ?? 50;
|
|
const offset = options?.offset ?? 0;
|
|
|
|
const whereClause =
|
|
options?.actions && options.actions.length > 0
|
|
? and(
|
|
eq(schema.commissionerAuditLog.seasonId, seasonId),
|
|
inArray(schema.commissionerAuditLog.action, options.actions)
|
|
)
|
|
: eq(schema.commissionerAuditLog.seasonId, seasonId);
|
|
|
|
const [entries, countRows] = await Promise.all([
|
|
db
|
|
.select()
|
|
.from(schema.commissionerAuditLog)
|
|
.where(whereClause)
|
|
.orderBy(desc(schema.commissionerAuditLog.createdAt))
|
|
.limit(limit)
|
|
.offset(offset),
|
|
db
|
|
.select({ count: sql<number>`count(*)::int` })
|
|
.from(schema.commissionerAuditLog)
|
|
.where(whereClause),
|
|
]);
|
|
|
|
const total = countRows[0]?.count ?? 0;
|
|
return { entries, total, hasMore: offset + entries.length < total };
|
|
}
|
|
|
|
/**
|
|
* Convenience wrapper that resolves the actor display name from the users table
|
|
* and writes a single audit log record. Call this after the main action succeeds.
|
|
*/
|
|
export async function logCommissionerAction(params: {
|
|
seasonId: string;
|
|
leagueId: string;
|
|
actorUserId: string;
|
|
action: AuditAction;
|
|
affectedTeamIds?: string[];
|
|
details?: Record<string, unknown>;
|
|
}): Promise<void> {
|
|
const user = await findUserById(params.actorUserId);
|
|
const actorDisplayName = user
|
|
? (getUserDisplayName(user) ?? params.actorUserId)
|
|
: params.actorUserId;
|
|
|
|
await createAuditLogEntry({
|
|
seasonId: params.seasonId,
|
|
leagueId: params.leagueId,
|
|
actorClerkId: params.actorUserId,
|
|
actorDisplayName,
|
|
action: params.action,
|
|
affectedTeamIds: params.affectedTeamIds ?? [],
|
|
details: params.details ?? {},
|
|
});
|
|
}
|