Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

set up SCIM webhook endpoints

Steven Tey93d0aca92d63
diff --git a/emails/project-invite.tsx b/emails/project-invite.tsx
index afea550647..6176e9a203 100644
--- a/emails/project-invite.tsx
+++ b/emails/project-invite.tsx
@@ -4,7 +4,6 @@ import {
Container,
Head,
Heading,
- Hr,
Html,
Img,
Preview,
@@ -25,8 +24,8 @@ export default function ProjectInvite({
email: string;
url: string;
projectName: string;
- projectUser: string;
- projectUserEmail: string;
+ projectUser: string | null;
+ projectUserEmail: string | null;
}) {
return (
<Html>
@@ -47,17 +46,24 @@ export default function ProjectInvite({
<Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
Join {projectName} on Dub
</Heading>
- <Text className="text-sm leading-6 text-black">
- <strong>{projectUser}</strong> (
- <Link
- className="text-blue-600 no-underline"
- href={`mailto:${projectUserEmail}`}
- >
- {projectUserEmail}
- </Link>
- ) has invited you to join the <strong>{projectName}</strong>{" "}
- project on Dub!
- </Text>
+ {projectUser && projectUserEmail ? (
+ <Text className="text-sm leading-6 text-black">
+ <strong>{projectUser}</strong> (
+ <Link
+ className="text-blue-600 no-underline"
+ href={`mailto:${projectUserEmail}`}
+ >
+ {projectUserEmail}
+ </Link>
+ ) has invited you to join the <strong>{projectName}</strong>{" "}
+ project on Dub!
+ </Text>
+ ) : (
+ <Text className="text-sm leading-6 text-black">
+ You have been invited to join the <strong>{projectName}</strong>{" "}
+ project on Dub!
+ </Text>
+ )}
<Section className="mb-8 text-center">
<Link
className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
diff --git a/lib/api/users.ts b/lib/api/users.ts
new file mode 100644
index 0000000000..9a2341bdbb
--- /dev/null
+++ b/lib/api/users.ts
@@ -0,0 +1,66 @@
+import { Session, hashToken } from "#/lib/auth";
+import prisma from "#/lib/prisma";
+import { sendEmail } from "emails";
+import { randomBytes } from "crypto";
+import ProjectInvite from "emails/project-invite";
+import { ProjectProps } from "#/lib/types";
+
+export async function inviteUser({
+ email,
+ project,
+ session,
+}: {
+ email: string;
+ project: ProjectProps;
+ session?: Session;
+}) {
+ // same method of generating a token as next-auth
+ const token = randomBytes(32).toString("hex");
+ const TWO_WEEKS_IN_SECONDS = 60 * 60 * 24 * 14;
+ const expires = new Date(Date.now() + TWO_WEEKS_IN_SECONDS * 1000);
+
+ // create a project invite record and a verification request token that lasts for a week
+ // here we use a try catch to account for the case where the user has already been invited
+ // for which `prisma.projectInvite.create()` will throw a unique constraint error
+ try {
+ await prisma.projectInvite.create({
+ data: {
+ email,
+ expires,
+ projectId: project.id,
+ },
+ });
+ } catch (error) {
+ if (error.code === "P2002") {
+ throw new Error("User has already been invited to this project");
+ }
+ }
+
+ await prisma.verificationToken.create({
+ data: {
+ identifier: email,
+ token: hashToken(token),
+ expires,
+ },
+ });
+
+ const params = new URLSearchParams({
+ callbackUrl: `${process.env.NEXTAUTH_URL}/${project.slug}`,
+ email,
+ token,
+ });
+
+ const url = `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;
+
+ return await sendEmail({
+ subject: "You've been invited to join a project on Dub",
+ email,
+ react: ProjectInvite({
+ email,
+ url,
+ projectName: project.name,
+ projectUser: session?.user.name || null,
+ projectUserEmail: session?.user.email || null,
+ }),
+ });
+}
diff --git a/pages/api/projects/[slug]/invites/index.tsx b/pages/api/projects/[slug]/invites/index.tsx
index 7205eac735..0d4969837c 100644
--- a/pages/api/projects/[slug]/invites/index.tsx
+++ b/pages/api/projects/[slug]/invites/index.tsx
@@ -1,8 +1,6 @@
-import { hashToken, withProjectAuth } from "#/lib/auth";
+import { inviteUser } from "#/lib/api/users";
+import { withProjectAuth } from "#/lib/auth";
import prisma from "#/lib/prisma";
-import { sendEmail } from "emails";
-import { randomBytes } from "crypto";
-import ProjectInvite from "emails/project-invite";
export default withProjectAuth(async (req, res, project, session) => {
// GET /api/projects/[slug]/invites - Get all pending invites for a project
@@ -57,54 +55,15 @@ export default withProjectAuth(async (req, res, project, session) => {
}
}
- // same method of generating a token as next-auth
- const token = randomBytes(32).toString("hex");
- const TWO_WEEKS_IN_SECONDS = 60 * 60 * 24 * 14;
- const expires = new Date(Date.now() + TWO_WEEKS_IN_SECONDS * 1000);
-
- // create a project invite record and a verification request token that lasts for a week
- // here we use a try catch to account for the case where the user has already been invited
- // for which `prisma.projectInvite.create()` will throw a unique constraint error
try {
- await prisma.projectInvite.create({
- data: {
- email,
- expires,
- projectId: project.id,
- },
- });
-
- await prisma.verificationToken.create({
- data: {
- identifier: email,
- token: hashToken(token),
- expires,
- },
- });
-
- const params = new URLSearchParams({
- callbackUrl: `${process.env.NEXTAUTH_URL}/${project.slug}`,
+ await inviteUser({
email,
- token,
+ project,
+ session,
});
-
- const url = `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;
-
- sendEmail({
- subject: "You've been invited to join a project on Dub",
- email,
- react: ProjectInvite({
- email,
- url,
- projectName: project.name,
- projectUser: session.user.name,
- projectUserEmail: session.user.email,
- }),
- });
-
return res.status(200).json({ message: "Invite sent" });
} catch (error) {
- return res.status(400).end("User already invited.");
+ return res.status(400).end(error);
}
// DELETE /api/projects/[slug]/invites – delete a pending invite
diff --git a/pages/api/scim/v2.0/[...directory].ts b/pages/api/scim/v2.0/[...directory].ts
index 4e75bb669a..1d180f067f 100644
--- a/pages/api/scim/v2.0/[...directory].ts
+++ b/pages/api/scim/v2.0/[...directory].ts
@@ -4,8 +4,9 @@ import prisma from "#/lib/prisma";
import type {
DirectorySyncEvent,
DirectorySyncRequest,
- User,
} from "@boxyhq/saml-jackson";
+import { inviteUser } from "#/lib/api/users";
+import { ProjectProps } from "#/lib/types";
// Fetch the auth token from the request headers
export const extractAuthToken = (req: NextApiRequest): string | null => {
@@ -50,86 +51,84 @@ export default async function handler(
res.status(status).json(data);
}
-const addUser = async ({
- data,
- projectId,
-}: {
- data: User;
- projectId: string;
-}) => {
- const user = await prisma.user.upsert({
+// Handle the SCIM events
+const handleEvents = async (event: DirectorySyncEvent) => {
+ const { event: action, tenant: projectId, data } = event;
+
+ const project = (await prisma.project.findUnique({
where: {
- email: data.email,
- },
- update: {
- name: `${data.first_name} ${data.last_name}`,
+ id: projectId,
},
- create: {
- name: `${data.first_name} ${data.last_name}`,
- email: data.email,
- },
- });
+ })) as ProjectProps;
- await Promise.all([
- // add to project
- prisma.projectUsers.upsert({
+ if (!project || project.plan !== "enterprise" || !("email" in data)) {
+ return;
+ }
+
+ const [userInProject, userInvited] = await Promise.all([
+ prisma.user.findFirst({
where: {
- userId_projectId: {
- userId: user.id,
- projectId,
+ email: data.email,
+ projects: {
+ some: {
+ projectId,
+ },
},
},
- update: {},
- create: {
- userId: user.id,
- projectId,
+ }),
+ await prisma.projectInvite.findUnique({
+ where: {
+ email_projectId: {
+ email: data.email,
+ projectId,
+ },
},
}),
- // send email invite
]);
-};
-// Handle the SCIM events
-const handleEvents = async (event: DirectorySyncEvent) => {
- const { event: action, tenant: projectId, data } = event;
- console.log({ action, projectId, data });
-
- // User has been created
- if (action === "user.created" && "email" in data) {
- await addUser({ data, projectId });
+ // User has been activated for the first time
+ if (action === "user.created" && !userInProject && !userInvited) {
+ await inviteUser({
+ email: data.email,
+ project,
+ });
}
- // User has been updated
- if (action === "user.updated" && "email" in data) {
- if (data.active === true) {
- await addUser({ data, projectId });
- return;
- }
-
- const user = await prisma.user.findUnique({
- where: {
+ // User has been activated
+ if (action === "user.updated" && data.active === true) {
+ if (!userInProject && !userInvited) {
+ await inviteUser({
email: data.email,
- },
- });
-
- if (!user) {
- return;
+ project,
+ });
}
+ }
- if (data.active === false) {
+ // User has been deactivated or deleted
+ if (
+ (action === "user.updated" && data.active === false) ||
+ action === "user.deleted"
+ ) {
+ if (userInProject) {
await prisma.projectUsers.delete({
where: {
userId_projectId: {
- userId: user.id,
+ userId: userInProject.id,
+ projectId,
+ },
+ },
+ });
+ }
+ if (userInvited) {
+ await prisma.projectInvite.delete({
+ where: {
+ email_projectId: {
+ email: data.email,
projectId,
},
},
});
}
}
-
- // User has been removed
- if (action === "user.deleted" && "email" in data) {
- // await deleteUser({ email: data.email });
- }
+ return;
};