brackt/app/models/audit-log.ts
Chris Parsons 5268e07365
Migrate auth from Clerk to BetterAuth (#354)
* Fix BetterAuth field mapping and add owner-prefixed team names

- Fix auth.server.ts: use camelCase Drizzle field names for BetterAuth
  adapter (was snake_case, causing user inserts to fail); add
  generateId: "uuid" so PostgreSQL UUID columns accept generated IDs
- Add prependOwnerToTeamName / stripOwnerFromTeamName utilities
- Invite join, league creation, and settings assign/remove all now
  manage the owner-prefix on team names atomically

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

* Complete BetterAuth migration: auth flows, rename, and cleanup

- Add /forgot-password and /reset-password pages (full password reset flow)
- Add 'Forgot password?' link on login page
- Fix register.tsx: add explicit window.location fallback after signUp
- Rename commissionerAuditLog.actorClerkId → actorUserId (migration 0084)
  and update all references in model, routes, components, and tests
- Rewrite docs/agents/auth.md to document BetterAuth (removes all Clerk refs)
- Update test fixtures and schema comments to remove Clerk ID references;
  use UUID-format IDs throughout test data
- Update docs/agents/domain-models.md ownerId description

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

* Fix BetterAuth ID generation, clean up review issues

- Set generateId: false so BetterAuth omits id from inserts; add
  $defaultFn(crypto.randomUUID) to accounts/sessions/verifications
  so Drizzle fills it in (fixes null id constraint violation on signup)
- Move renameTeam to static import; rename before removeTeamOwner so
  a failed rename leaves owner intact rather than leaving a stale prefix
- Clarify stripOwnerFromTeamName toTitleCase assumption in comment
- Annotate reset-password token fallback to explain loader guarantee

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 10:03:50 -07:00

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,
actorUserId: params.actorUserId,
actorDisplayName,
action: params.action,
affectedTeamIds: params.affectedTeamIds ?? [],
details: params.details ?? {},
});
}