-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathupdate-domain.ts
More file actions
82 lines (66 loc) · 1.98 KB
/
update-domain.ts
File metadata and controls
82 lines (66 loc) · 1.98 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
73
74
75
76
77
78
79
80
81
82
"use server";
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { organizations } from "@cap/database/schema";
import type { Organisation } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { addDomain, checkDomainStatus } from "./domain-utils";
export async function updateDomain(
domain: string,
organizationId: Organisation.OrganisationId,
) {
const user = await getCurrentUser();
if (!user) {
throw new Error("Unauthorized");
}
//check user subscription to prevent abuse
const isSubscribed = user.stripeSubscriptionStatus === "active";
if (!isSubscribed) {
throw new Error("User is not subscribed");
}
const [organization] = await db()
.select()
.from(organizations)
.where(eq(organizations.id, organizationId));
if (!organization || organization.ownerId !== user.id) {
throw new Error("Only the owner can update the custom domain");
}
// Check if domain is already being used by another organization
const existingDomain = await db()
.select()
.from(organizations)
.where(eq(organizations.customDomain, domain))
.limit(1);
if (existingDomain.length > 0 && existingDomain[0]?.id !== organizationId) {
throw new Error("This domain is already being used.");
}
try {
const addDomainResponse = await addDomain(domain);
if (addDomainResponse.error) {
throw new Error(addDomainResponse.error.message);
}
await db()
.update(organizations)
.set({
customDomain: domain,
domainVerified: null,
})
.where(eq(organizations.id, organizationId));
const status = await checkDomainStatus(domain);
if (status.verified) {
await db()
.update(organizations)
.set({
domainVerified: new Date(),
})
.where(eq(organizations.id, organizationId));
}
revalidatePath("/dashboard/settings/organization");
return status;
} catch (error) {
if (error instanceof Error) {
throw new Error(error.message);
}
}
}