81 lines
2.1 KiB
TypeScript
81 lines
2.1 KiB
TypeScript
"use server";
|
|
|
|
import { createClient } from "@/lib/supabase/server";
|
|
import { revalidatePath } from "next/cache";
|
|
|
|
export async function inviteUser(formData: FormData) {
|
|
const email = formData.get("email") as string;
|
|
if (!email) {
|
|
throw new Error("Email is required");
|
|
}
|
|
|
|
const supabase = await createClient();
|
|
const { data: userData, error: userError } = await supabase.auth.getUser();
|
|
|
|
if (userError || !userData.user) {
|
|
throw new Error("Unauthorized");
|
|
}
|
|
|
|
const { data: profile } = await supabase
|
|
.from("profiles")
|
|
.select("organization_id, role")
|
|
.eq("id", userData.user.id)
|
|
.single();
|
|
|
|
if (!profile || profile.role !== "owner" || !profile.organization_id) {
|
|
throw new Error("Only organization owners can invite new members");
|
|
}
|
|
|
|
const { error: inviteError } = await supabase
|
|
.from("invitations")
|
|
.insert([
|
|
{
|
|
email,
|
|
organization_id: profile.organization_id,
|
|
invited_by: userData.user.id,
|
|
},
|
|
]);
|
|
|
|
if (inviteError) {
|
|
console.error("Error creating invitation:", inviteError);
|
|
throw new Error("Failed to create invitation");
|
|
}
|
|
|
|
revalidatePath("/dashboard/settings/team");
|
|
}
|
|
|
|
export async function revokeInvitation(formData: FormData) {
|
|
const id = formData.get("id") as string;
|
|
if (!id) {
|
|
throw new Error("Invitation ID is required");
|
|
}
|
|
|
|
const supabase = await createClient();
|
|
const { data: userData, error: userError } = await supabase.auth.getUser();
|
|
|
|
if (userError || !userData.user) {
|
|
throw new Error("Unauthorized");
|
|
}
|
|
|
|
const { data: profile } = await supabase
|
|
.from("profiles")
|
|
.select("organization_id, role")
|
|
.eq("id", userData.user.id)
|
|
.single();
|
|
|
|
if (!profile || profile.role !== "owner" || !profile.organization_id) {
|
|
throw new Error("Only organization owners can revoke invitations");
|
|
}
|
|
|
|
const { error: deleteError } = await supabase
|
|
.from("invitations")
|
|
.delete()
|
|
.match({ id, organization_id: profile.organization_id });
|
|
|
|
if (deleteError) {
|
|
console.error("Error revoking invitation:", deleteError);
|
|
throw new Error("Failed to revoke invitation");
|
|
}
|
|
|
|
revalidatePath("/dashboard/settings/team");
|
|
}
|