98 lines
2.8 KiB
TypeScript
98 lines
2.8 KiB
TypeScript
import { fail, handleOptions, json } from "../_shared/http.ts";
|
|
import { createServiceClient, requireUser } from "../_shared/supabase.ts";
|
|
|
|
function generateInviteToken(): string {
|
|
const bytes = crypto.getRandomValues(new Uint8Array(12));
|
|
return Array.from(bytes)
|
|
.map((b) => b.toString(16).padStart(2, "0"))
|
|
.join("");
|
|
}
|
|
|
|
Deno.serve(async (req) => {
|
|
const preflight = handleOptions(req);
|
|
if (preflight) return preflight;
|
|
|
|
if (req.method !== "POST") return fail("Method not allowed", 405);
|
|
|
|
const { user, error: userError } = await requireUser(req);
|
|
if (!user) return fail(userError ?? "Unauthorized", 401);
|
|
|
|
let body: { organization_id?: string; max_uses?: number; expires_in_days?: number };
|
|
try {
|
|
body = await req.json();
|
|
} catch {
|
|
return fail("Invalid JSON body");
|
|
}
|
|
|
|
const organizationId = (body.organization_id ?? "").trim();
|
|
if (!organizationId) return fail("organization_id is required");
|
|
|
|
const maxUses = Number.isInteger(body.max_uses) ? Number(body.max_uses) : 1;
|
|
if (maxUses < 1 || maxUses > 1000) return fail("max_uses must be between 1 and 1000");
|
|
|
|
const expiresInDays = Number.isInteger(body.expires_in_days)
|
|
? Number(body.expires_in_days)
|
|
: 7;
|
|
if (expiresInDays < 1 || expiresInDays > 365) {
|
|
return fail("expires_in_days must be between 1 and 365");
|
|
}
|
|
|
|
const service = createServiceClient();
|
|
const { data: member, error: memberError } = await service
|
|
.from("organization_members")
|
|
.select("role")
|
|
.eq("organization_id", organizationId)
|
|
.eq("user_id", user.id)
|
|
.maybeSingle();
|
|
|
|
if (memberError) return fail(memberError.message, 400);
|
|
if (!member || !["owner", "admin"].includes(member.role)) return fail("forbidden", 403);
|
|
|
|
const expiresAt = new Date(
|
|
Date.now() + expiresInDays * 24 * 60 * 60 * 1000,
|
|
).toISOString();
|
|
|
|
let invite:
|
|
| {
|
|
id: string;
|
|
token: string;
|
|
organization_id: string;
|
|
max_uses: number;
|
|
uses_count: number;
|
|
expires_at: string | null;
|
|
revoked: boolean;
|
|
created_at: string;
|
|
}
|
|
| null = null;
|
|
let lastError: string | null = null;
|
|
|
|
for (let i = 0; i < 5; i++) {
|
|
const token = generateInviteToken();
|
|
const { data, error } = await service
|
|
.from("organization_invites")
|
|
.insert({
|
|
token,
|
|
organization_id: organizationId,
|
|
created_by: user.id,
|
|
role: "member",
|
|
max_uses: maxUses,
|
|
expires_at: expiresAt,
|
|
})
|
|
.select("id, token, organization_id, max_uses, uses_count, expires_at, revoked, created_at")
|
|
.single();
|
|
|
|
if (!error) {
|
|
invite = data;
|
|
break;
|
|
}
|
|
|
|
lastError = error.message;
|
|
if (error.code != "23505") break;
|
|
}
|
|
|
|
if (!invite) return fail(lastError ?? "Could not create invite", 400);
|
|
|
|
return json({
|
|
invite,
|
|
});
|
|
});
|