55 createWebsiteResponseSchema ,
66} from "@api/schemas/website" ;
77import { createDefaultWebsiteKeys } from "@api/db/queries/api-keys" ;
8- import { eq } from "drizzle-orm" ;
8+ import { and , eq } from "drizzle-orm" ;
99import { nanoid } from "nanoid" ;
10+ import { TRPCError } from "@trpc/server" ;
1011
1112export const websiteRouter = createTRPCRouter ( {
1213 create : protectedProcedure
@@ -16,22 +17,49 @@ export const websiteRouter = createTRPCRouter({
1617 let slug = input . name . trim ( ) . toLowerCase ( ) . replace ( / / g, "-" ) ;
1718
1819 // Check if website with same slug already exists
19- const existingWebsite = await db . query . website . findFirst ( {
20- where : eq ( website . slug , slug ) ,
21- } ) ;
20+ const [ existingSlugWebsite , existingDomainWebsite ] = await Promise . all ( [
21+ db . query . website . findFirst ( {
22+ where : eq ( website . slug , slug ) ,
23+ } ) ,
24+ db . query . website . findFirst ( {
25+ where : and (
26+ eq ( website . domain , input . domain ) ,
27+ eq ( website . isDomainOwnershipVerified , true )
28+ ) ,
29+ } ) ,
30+ ] ) ;
2231
2332 // If website with same slug already exists, add a random suffix to the slug
24- if ( existingWebsite ) {
33+ if ( existingSlugWebsite ) {
2534 slug = `${ slug } -${ nanoid ( 4 ) } ` ;
2635 }
2736
37+ // If website with same verified domain already exists, error, the user cannot use that domain
38+ if ( existingDomainWebsite ) {
39+ throw new TRPCError ( {
40+ code : "BAD_REQUEST" ,
41+ message : "Domain already in use by another website" ,
42+ } ) ;
43+ }
44+
45+ const userEmailDomain = user . email . split ( "@" ) [ 1 ] ;
46+
47+ // TODO: Add a better verification process for domain ownership
48+ // If the user's email domain is the same as the website domain, we can assume that the user owns the domain for now
49+ const isDomainOwnershipVerified = userEmailDomain === input . domain ;
50+
2851 const [ createdWebsite ] = await db
2952 . insert ( website )
3053 . values ( {
3154 name : input . name ,
3255 organizationId : input . organizationId ,
3356 installationTarget : input . installationTarget ,
34- whitelistedDomains : [ input . domain , "http://localhost:3000" ] ,
57+ domain : input . domain ,
58+ isDomainOwnershipVerified,
59+ whitelistedDomains : [
60+ `https://${ input . domain } ` ,
61+ "http://localhost:3000" ,
62+ ] ,
3563 slug,
3664 } )
3765 . returning ( ) ;
0 commit comments