import { json, error } from '@sveltejs/kit'; import type { RequestHandler } from './$types.js'; import { withTenant } from '$lib/server/rls.js'; import { requireTenantAdmin } from '$lib/server/guards.js'; import crypto from 'crypto'; // List all invites for the current tenant export const GET: RequestHandler = async ({ locals }) => { const tenant = locals.tenant; if (!tenant) throw error(400, 'Unknown tenant'); requireTenantAdmin(locals.user); const invites = await withTenant(tenant.id, async (tx) => { return tx.tenantInvite.findMany({ where: { tenantId: tenant.id }, orderBy: { expiresAt: 'desc' } }); }); return json({ invites }); }; // Create a new invite export const POST: RequestHandler = async ({ locals, request }) => { const tenant = locals.tenant; if (!tenant) throw error(400, 'Unknown tenant'); requireTenantAdmin(locals.user); const body = await request.json().catch(() => ({})); const role = body.role === 'ADMIN' ? 'ADMIN' : 'MEMBER'; const maxUses = typeof body.maxUses === 'number' && body.maxUses > 0 ? body.maxUses : null; const expiresInDays = typeof body.expiresInDays === 'number' && body.expiresInDays > 0 ? body.expiresInDays : 7; const code = crypto.randomBytes(9).toString('base64url'); const expiresAt = new Date(Date.now() + expiresInDays * 24 * 60 * 60 * 1000); const invite = await withTenant(tenant.id, async (tx) => { return tx.tenantInvite.create({ data: { tenantId: tenant.id, code, role, expiresAt, createdBy: locals.user!.id, maxUses } }); }); return json({ invite }, { status: 201 }); };