2025-10-11 00:29:04 -07:00
|
|
|
import { eq, and } from "drizzle-orm";
|
|
|
|
|
import { database } from "~/database/context";
|
|
|
|
|
import * as schema from "~/database/schema";
|
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 { isUserAdmin } from "~/models/user";
|
2025-10-11 00:29:04 -07:00
|
|
|
|
|
|
|
|
export type Commissioner = typeof schema.commissioners.$inferSelect;
|
|
|
|
|
export type NewCommissioner = typeof schema.commissioners.$inferInsert;
|
|
|
|
|
|
|
|
|
|
export async function createCommissioner(
|
|
|
|
|
data: NewCommissioner
|
|
|
|
|
): Promise<Commissioner> {
|
|
|
|
|
const db = database();
|
|
|
|
|
const [commissioner] = await db
|
|
|
|
|
.insert(schema.commissioners)
|
|
|
|
|
.values(data)
|
|
|
|
|
.returning();
|
|
|
|
|
return commissioner;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function findCommissionersByLeagueId(
|
|
|
|
|
leagueId: string
|
|
|
|
|
): Promise<Commissioner[]> {
|
|
|
|
|
const db = database();
|
|
|
|
|
return await db.query.commissioners.findMany({
|
|
|
|
|
where: eq(schema.commissioners.leagueId, leagueId),
|
|
|
|
|
orderBy: (commissioners, { asc }) => [asc(commissioners.createdAt)],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function findCommissionersByUserId(
|
|
|
|
|
userId: string
|
|
|
|
|
): Promise<Commissioner[]> {
|
|
|
|
|
const db = database();
|
|
|
|
|
return await db.query.commissioners.findMany({
|
|
|
|
|
where: eq(schema.commissioners.userId, userId),
|
|
|
|
|
orderBy: (commissioners, { desc }) => [desc(commissioners.createdAt)],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
Grant sitewide admins commissioner-level access in leagues (#162)
* Grant sitewide admins commissioner-level access in leagues
- `isCommissioner()` now returns true for site admins, covering all
commissioner-gated loaders (league home, settings, sport season detail)
and draft API routes (start, pause, resume, rollback, replace-pick,
force-autopick, force-manual-pick, adjust-time-bank, make-pick)
- Added `hasCommissionerRecord()` (DB-only, no admin bypass) for the
"already a commissioner" duplicate-entry check in the settings action,
preventing a false positive when adding a site admin as commissioner
- `isCommissioner()` now runs the admin check and DB query in parallel
via Promise.all to avoid a serial roundtrip on every check
- Added "admin" to the `picked_by_type` enum (migration 0049) so picks
forced by a site admin are recorded accurately in the audit log rather
than as "commissioner"
- 8 unit tests covering both isCommissioner and hasCommissionerRecord
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix draft.force-manual-pick tests broken by isUserAdminByClerkId
The route now calls isUserAdminByClerkId which hits database().query.users,
but the test's mock DB had no query.users entry. Add a vi.mock for
~/models/user and default isUserAdminByClerkId to false in beforeEach.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 00:41:56 -07:00
|
|
|
export async function hasCommissionerRecord(
|
2025-10-11 00:29:04 -07:00
|
|
|
leagueId: string,
|
|
|
|
|
userId: string
|
|
|
|
|
): Promise<boolean> {
|
|
|
|
|
const db = database();
|
|
|
|
|
const commissioner = await db.query.commissioners.findFirst({
|
|
|
|
|
where: and(
|
|
|
|
|
eq(schema.commissioners.leagueId, leagueId),
|
|
|
|
|
eq(schema.commissioners.userId, userId)
|
|
|
|
|
),
|
|
|
|
|
});
|
|
|
|
|
return !!commissioner;
|
|
|
|
|
}
|
|
|
|
|
|
Grant sitewide admins commissioner-level access in leagues (#162)
* Grant sitewide admins commissioner-level access in leagues
- `isCommissioner()` now returns true for site admins, covering all
commissioner-gated loaders (league home, settings, sport season detail)
and draft API routes (start, pause, resume, rollback, replace-pick,
force-autopick, force-manual-pick, adjust-time-bank, make-pick)
- Added `hasCommissionerRecord()` (DB-only, no admin bypass) for the
"already a commissioner" duplicate-entry check in the settings action,
preventing a false positive when adding a site admin as commissioner
- `isCommissioner()` now runs the admin check and DB query in parallel
via Promise.all to avoid a serial roundtrip on every check
- Added "admin" to the `picked_by_type` enum (migration 0049) so picks
forced by a site admin are recorded accurately in the audit log rather
than as "commissioner"
- 8 unit tests covering both isCommissioner and hasCommissionerRecord
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix draft.force-manual-pick tests broken by isUserAdminByClerkId
The route now calls isUserAdminByClerkId which hits database().query.users,
but the test's mock DB had no query.users entry. Add a vi.mock for
~/models/user and default isUserAdminByClerkId to false in beforeEach.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 00:41:56 -07:00
|
|
|
export async function isCommissioner(
|
|
|
|
|
leagueId: string,
|
|
|
|
|
userId: string
|
|
|
|
|
): Promise<boolean> {
|
|
|
|
|
const db = database();
|
|
|
|
|
const [isAdmin, commissioner] = await Promise.all([
|
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
|
|
|
isUserAdmin(userId),
|
Grant sitewide admins commissioner-level access in leagues (#162)
* Grant sitewide admins commissioner-level access in leagues
- `isCommissioner()` now returns true for site admins, covering all
commissioner-gated loaders (league home, settings, sport season detail)
and draft API routes (start, pause, resume, rollback, replace-pick,
force-autopick, force-manual-pick, adjust-time-bank, make-pick)
- Added `hasCommissionerRecord()` (DB-only, no admin bypass) for the
"already a commissioner" duplicate-entry check in the settings action,
preventing a false positive when adding a site admin as commissioner
- `isCommissioner()` now runs the admin check and DB query in parallel
via Promise.all to avoid a serial roundtrip on every check
- Added "admin" to the `picked_by_type` enum (migration 0049) so picks
forced by a site admin are recorded accurately in the audit log rather
than as "commissioner"
- 8 unit tests covering both isCommissioner and hasCommissionerRecord
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Fix draft.force-manual-pick tests broken by isUserAdminByClerkId
The route now calls isUserAdminByClerkId which hits database().query.users,
but the test's mock DB had no query.users entry. Add a vi.mock for
~/models/user and default isUserAdminByClerkId to false in beforeEach.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 00:41:56 -07:00
|
|
|
db.query.commissioners.findFirst({
|
|
|
|
|
where: and(
|
|
|
|
|
eq(schema.commissioners.leagueId, leagueId),
|
|
|
|
|
eq(schema.commissioners.userId, userId)
|
|
|
|
|
),
|
|
|
|
|
}),
|
|
|
|
|
]);
|
|
|
|
|
return isAdmin || !!commissioner;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-20 08:45:09 -08:00
|
|
|
export async function countCommissionersByLeagueId(
|
|
|
|
|
leagueId: string
|
|
|
|
|
): Promise<number> {
|
|
|
|
|
const db = database();
|
|
|
|
|
const commissioners = await db.query.commissioners.findMany({
|
|
|
|
|
where: eq(schema.commissioners.leagueId, leagueId),
|
|
|
|
|
});
|
|
|
|
|
return commissioners.length;
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-11 00:29:04 -07:00
|
|
|
export async function deleteCommissioner(id: string): Promise<void> {
|
|
|
|
|
const db = database();
|
|
|
|
|
await db.delete(schema.commissioners).where(eq(schema.commissioners.id, id));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function removeCommissionerByLeagueAndUser(
|
|
|
|
|
leagueId: string,
|
|
|
|
|
userId: string
|
|
|
|
|
): Promise<void> {
|
|
|
|
|
const db = database();
|
|
|
|
|
await db
|
|
|
|
|
.delete(schema.commissioners)
|
|
|
|
|
.where(
|
|
|
|
|
and(
|
|
|
|
|
eq(schema.commissioners.leagueId, leagueId),
|
|
|
|
|
eq(schema.commissioners.userId, userId)
|
|
|
|
|
)
|
|
|
|
|
);
|
|
|
|
|
}
|