-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathremove-member.ts
More file actions
72 lines (63 loc) · 1.81 KB
/
remove-member.ts
File metadata and controls
72 lines (63 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"use server";
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { organizationMembers, organizations } from "@cap/database/schema";
import type { Organisation } from "@cap/web-domain";
import { and, eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
export async function removeOrganizationMember(
memberId: string,
organizationId: Organisation.OrganisationId,
) {
const user = await getCurrentUser();
if (!user) throw new Error("Unauthorized");
const [organization] = await db()
.select({ id: organizations.id })
.from(organizations)
.where(eq(organizations.id, organizationId))
.limit(1);
if (!organization) {
throw new Error("Organization not found");
}
const [ownerMembership] = await db()
.select({ id: organizationMembers.id })
.from(organizationMembers)
.where(
and(
eq(organizationMembers.organizationId, organizationId),
eq(organizationMembers.userId, user.id),
eq(organizationMembers.role, "owner"),
),
)
.limit(1);
if (!ownerMembership) {
throw new Error("Only the owner can remove organization members");
}
const [member] = await db()
.select()
.from(organizationMembers)
.where(
and(
eq(organizationMembers.id, memberId),
eq(organizationMembers.organizationId, organizationId),
),
)
.limit(1);
if (!member) {
throw new Error("Member not found");
}
if (member.userId === user.id) {
throw new Error("Owner cannot remove themselves");
}
const [result] = await db()
.delete(organizationMembers)
.where(
and(
eq(organizationMembers.id, memberId),
eq(organizationMembers.organizationId, organizationId),
),
);
if (result.affectedRows === 0) throw new Error("Member not found");
revalidatePath("/dashboard/settings/organization");
return { success: true };
}