mike-backend / backend /src /lib /users.ts
bardd's picture
Deploy Mike backend-only Space
06671aa verified
Raw History Blame Contribute Delete
1.56 kB
import { createServerSupabase } from "./supabase";
type Db = ReturnType<typeof createServerSupabase>;
export interface UserMaps {
/** user id -> email (lowercased keys handled by callers) */
byId: Map<string, string | null>;
/** lowercase email -> user id */
emailToId: Map<string, string>;
}
/**
* Load all registered auth.users into id<->email lookup maps.
* The shim ignores the perPage argument; this mirrors projects.ts:171-180.
* Safe for the pilot (<=6 users). For larger deployments, page or add a bulk RPC.
*/
export async function loadUserMaps(db: Db): Promise<UserMaps> {
const { data } = await db.auth.admin.listUsers({ perPage: 1000 });
const users = data?.users ?? [];
const byId = new Map<string, string | null>();
const emailToId = new Map<string, string>();
for (const u of users) {
byId.set(u.id, u.email ?? null);
if (u.email) emailToId.set(u.email.toLowerCase(), u.id);
}
return { byId, emailToId };
}
/** Resolve a single user id to its signup email. Loads all users (pilot scale). */
export async function resolveEmailByUserId(
db: Db,
userId: string | null | undefined,
): Promise<string | null> {
if (!userId) return null;
const { byId } = await loadUserMaps(db);
return byId.get(userId) ?? null;
}
/** Resolve a single (case-insensitive) email to its user id. Loads all users. */
export async function resolveUserIdByEmail(
db: Db,
email: string,
): Promise<string | null> {
const { emailToId } = await loadUserMaps(db);
return emailToId.get(email.toLowerCase()) ?? null;
}