Files
LivingDexTracker/src/lib/utils/auth.ts
T
Josh Creek 3a2c18bbeb fix: repair defects surfaced by gating CI on lint and typecheck
`npm run check` reported 15 errors and `npm run lint` 20, all pre-existing, so
neither gate could pass. Fixing them turned up three real bugs:

- SignOut destructured `{ error }` off `.then(() => {})`, which resolves to
  undefined, so every sign-out threw a TypeError - after the signed-out event had
  already been emitted. Sign-out also left the user on the protected page they
  were on, still showing its content; it now returns them to the home page and
  re-runs the server loads.

- SignUp passed `redirectTo`, which is not a signUp option and was silently
  ignored, so the confirmation link has always used Supabase's configured site
  URL. Documented rather than changed, since pointing it elsewhere needs an
  absolute allow-listed URL.

- The Pokédex page tracked totalRecordsCreated but never passed it to the box
  view, so the "Processed N entries so far" progress message never rendered.

The rest is typing and dead code: cookie callback parameters in hooks.server.ts
and +layout.ts, the untyped supabase props, a query-builder type that made
PostgREST rows untyped downstream, an unused session destructure, and
`while (true)` paging loops rewritten as `for (;;)`.
2026-09-13 17:38:42 +01:00

30 lines
811 B
TypeScript

import type { RequestEvent } from '@sveltejs/kit';
import { error } from '@sveltejs/kit';
/**
* Validates the user session and returns the authenticated user ID
* Throws a 401 error if the user is not authenticated
*/
export async function requireAuth(event: RequestEvent): Promise<string> {
const { session, user } = await event.locals.safeGetSession();
if (!session || !user) {
throw error(401, 'Authentication required');
}
return user.id;
}
/**
* Optionally validates the user session and returns the user ID if authenticated
* Returns null if not authenticated (no error thrown)
*/
export async function getOptionalUserId(event: RequestEvent): Promise<string | null> {
try {
const { user } = await event.locals.safeGetSession();
return user?.id || null;
} catch {
return null;
}
}