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.

simplify to just ssoEmailDomain

Steven Tey9cd79ba57136
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
index 601a580172..392f73d927 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
@@ -33,7 +33,7 @@ const updateWorkspaceSchema = createWorkspaceSchema
z.null(),
])
.optional(),
- enforceSAML: z.boolean().optional(),
+ ssoEmailDomain: z.string().nullish(),
})
.partial();
@@ -85,7 +85,7 @@ export const PATCH = withWorkspace(
conversionEnabled,
allowedHostnames,
publishableKey,
- enforceSAML,
+ ssoEmailDomain,
} = await updateWorkspaceSchema.parseAsync(await parseRequestBody(req));
if (["free", "pro"].includes(workspace.plan) && conversionEnabled) {
@@ -95,13 +95,6 @@ export const PATCH = withWorkspace(
});
}
- if (enforceSAML && workspace.plan !== "enterprise") {
- throw new DubApiError({
- code: "forbidden",
- message: "SAML SSO is only available on enterprise plans.",
- });
- }
-
const validHostnames = allowedHostnames
? validateAllowedHostnames(allowedHostnames)
: undefined;
@@ -113,38 +106,27 @@ export const PATCH = withWorkspace(
)
: null;
- // Handle SAML SSO enforcement
- let ssoEmailDomain: string | null | undefined = undefined;
- let ssoEnforcedAt: Date | null | undefined = undefined;
+ if (ssoEmailDomain) {
+ if (workspace.plan !== "enterprise") {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "SAML SSO is only available on enterprise plans.",
+ });
+ }
- if (enforceSAML !== undefined) {
- if (enforceSAML) {
- ssoEmailDomain = session.user.email.split("@")[1];
- ssoEnforcedAt = new Date();
+ // Check if SAML is configured before enforcing ssoEmailDomain
+ const { apiController } = await jackson();
- // Check if SAML is configured before enforcing
- const { apiController } = await jackson();
+ const connections = await apiController.getConnections({
+ tenant: workspace.id,
+ product: "Dub",
+ });
- const connections = await apiController.getConnections({
- tenant: workspace.id,
- product: "Dub",
+ if (connections.length === 0) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "SAML SSO is not configured for this workspace.",
});
-
- if (connections.length === 0) {
- throw new DubApiError({
- code: "forbidden",
- message: "SAML SSO is not configured for this workspace.",
- });
- }
- } else {
- ssoEnforcedAt = null;
- ssoEmailDomain = null;
- }
-
- // Don't overwrite the SSO enforcement if it's already set
- if (enforceSAML && workspace.ssoEnforcedAt) {
- ssoEnforcedAt = undefined;
- ssoEmailDomain = undefined;
}
}
@@ -162,7 +144,6 @@ export const PATCH = withWorkspace(
allowedHostnames: validHostnames,
}),
...(publishableKey !== undefined && { publishableKey }),
- ...(enforceSAML !== undefined && { ssoEnforcedAt }),
...(ssoEmailDomain !== undefined && { ssoEmailDomain }),
},
include: {
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
index f5a5c9d62c..27282f9203 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
@@ -93,12 +93,13 @@ export const DELETE = withWorkspace(
id: workspace.id,
},
data: {
- ssoEnforcedAt: null,
ssoEmailDomain: null,
},
});
- return NextResponse.json({ response: "removed SAML connection" });
+ return NextResponse.json({
+ response: "Successfully removed SAML connection",
+ });
},
{
requiredPermissions: ["workspaces.write"],
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/saml.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/saml.tsx
index 25fa745042..3865a90412 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/saml.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/saml.tsx
@@ -8,32 +8,35 @@ import { ThreeDots } from "@/ui/shared/icons";
import {
Button,
IconMenu,
+ InfoTooltip,
Popover,
- Switch,
TooltipContent,
- useOptimisticUpdate,
} from "@dub/ui";
import { SAML_PROVIDERS } from "@dub/utils";
import { Lock, ShieldOff } from "lucide-react";
-import { useCallback, useMemo, useState } from "react";
+import { useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+
+type FormData = {
+ ssoEmailDomain: string;
+};
export function SAML() {
- const { plan, id, ssoEnforcedAt } = useWorkspace();
+ const { plan, id, ssoEmailDomain, mutate } = useWorkspace();
const { SAMLModal, setShowSAMLModal } = useSAMLModal();
const { RemoveSAMLModal, setShowRemoveSAMLModal } = useRemoveSAMLModal();
const { provider, configured, loading } = useSAML();
const [openPopover, setOpenPopover] = useState(false);
const {
- data: workspaceData,
- isLoading,
- update,
- } = useOptimisticUpdate<{
- ssoEnforcedAt: Date | null;
- }>(`/api/workspaces/${id}`, {
- loading: "Saving SAML enforcement setting...",
- success: "SAML enforcement has been updated successfully.",
- error: "Unable to update SAML enforcement. Please try again.",
+ register,
+ handleSubmit,
+ formState: { isDirty, isSubmitting },
+ reset,
+ } = useForm<FormData>({
+ defaultValues: {
+ ssoEmailDomain: ssoEmailDomain || "",
+ },
});
const currentProvider = useMemo(
@@ -74,37 +77,35 @@ export function SAML() {
}
}, [provider, configured, loading]);
- const handleSSOEnforcementChange = useCallback(
- async (enforceSAML: boolean) => {
- if (!configured) {
- return;
- }
-
- const updateWorkspace = async () => {
- const response = await fetch(`/api/workspaces/${id}`, {
- method: "PATCH",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ enforceSAML }),
- });
+ const onSubmit = async (data: FormData) => {
+ if (!configured) {
+ return;
+ }
- if (!response.ok) {
- const { error } = await response.json();
- throw new Error(error.message || "Failed to update workspace.");
- }
+ try {
+ const response = await fetch(`/api/workspaces/${id}`, {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ ssoEmailDomain: data.ssoEmailDomain.trim() || null,
+ }),
+ });
- return {
- ssoEnforcedAt: enforceSAML ? new Date() : null,
- };
- };
+ if (!response.ok) {
+ const { error } = await response.json();
+ throw new Error(error.message || "Failed to update email domain.");
+ }
- await update(updateWorkspace, {
- ssoEnforcedAt: enforceSAML ? new Date() : null,
- });
- },
- [id, configured, update],
- );
+ // Reset form to mark as not dirty
+ await mutate();
+ reset(data);
+ } catch (error) {
+ console.error("Error updating email domain:", error);
+ alert("Failed to update email domain. Please try again.");
+ }
+ };
return (
<>
@@ -197,18 +198,34 @@ export function SAML() {
<div className="rounded-b-lg border-t border-neutral-200 bg-neutral-50 px-3 py-5 sm:px-10">
{configured ? (
- <div className="flex items-center justify-between">
- <label className="text-sm font-medium text-neutral-700">
- Require SAML SSO authentication for all members of the
- workspace.
- </label>
- <Switch
- checked={!!(workspaceData?.ssoEnforcedAt || ssoEnforcedAt)}
- loading={isLoading}
- disabled={plan !== "enterprise"}
- fn={handleSSOEnforcementChange}
- />
- </div>
+ <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
+ <div className="flex items-center space-x-2">
+ <label
+ htmlFor="ssoEmailDomain"
+ className="text-sm font-medium text-neutral-700"
+ >
+ Email Domain for SAML Enforcement
+ </label>
+ <InfoTooltip content="Users with email addresses from this domain will be required to authenticate via SAML SSO. Leave empty to allow all users to choose their authentication method." />
+ </div>
+ <div className="flex items-center space-x-3">
+ <input
+ {...register("ssoEmailDomain")}
+ id="ssoEmailDomain"
+ type="text"
+ placeholder="example.com"
+ className="w-64 rounded-md border border-neutral-300 px-3 py-2 text-sm placeholder-neutral-400 focus:border-black focus:outline-none focus:ring-black"
+ disabled={plan !== "enterprise"}
+ />
+ <Button
+ type="submit"
+ text="Save"
+ loading={isSubmitting}
+ disabled={plan !== "enterprise" || !isDirty}
+ className="w-fit"
+ />
+ </div>
+ </form>
) : (
<div className="flex items-center justify-between">
<a
diff --git a/apps/web/lib/actions/check-account-exists.ts b/apps/web/lib/actions/check-account-exists.ts
index 37059b9cd7..570e0d359d 100644
--- a/apps/web/lib/actions/check-account-exists.ts
+++ b/apps/web/lib/actions/check-account-exists.ts
@@ -3,9 +3,7 @@
import { getIP } from "@/lib/api/utils/get-ip";
import { ratelimit } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
-import { APP_HOSTNAMES } from "@dub/utils";
-import { headers } from "next/headers";
-import { isGenericEmail } from "../is-generic-email";
+import { isSamlEnforcedForEmailDomain } from "../api/workspaces/is-saml-enforced-for-email-domain";
import z from "../zod";
import { emailSchema } from "../zod/schemas/auth";
import { throwIfAuthenticated } from "./auth/throw-if-authenticated";
@@ -30,13 +28,7 @@ export const checkAccountExistsAction = actionClient
throw new Error("Too many requests. Please try again later.");
}
- // Check SAML enforcement
- const hostname = headers().get("host");
- const emailDomain = email.split("@")[1];
- const shouldCheckSAML =
- hostname && APP_HOSTNAMES.has(hostname) && !isGenericEmail(email);
-
- const [user, workspace] = await Promise.all([
+ const [user, isSamlEnforced] = await Promise.all([
prisma.user.findUnique({
where: {
email,
@@ -46,21 +38,12 @@ export const checkAccountExistsAction = actionClient
},
}),
- shouldCheckSAML
- ? prisma.project.findUnique({
- where: {
- ssoEmailDomain: emailDomain,
- },
- select: {
- ssoEnforcedAt: true,
- },
- })
- : Promise.resolve(null),
+ isSamlEnforcedForEmailDomain(email),
]);
return {
accountExists: !!user,
hasPassword: !!user?.passwordHash,
- requireSAML: !!workspace?.ssoEnforcedAt,
+ requireSAML: isSamlEnforced,
};
});
diff --git a/apps/web/lib/api/workspaces/is-saml-enforced-for-email-domain.ts b/apps/web/lib/api/workspaces/is-saml-enforced-for-email-domain.ts
new file mode 100644
index 0000000000..8c5b832108
--- /dev/null
+++ b/apps/web/lib/api/workspaces/is-saml-enforced-for-email-domain.ts
@@ -0,0 +1,27 @@
+import { prisma } from "@dub/prisma";
+import { APP_HOSTNAMES } from "@dub/utils";
+import { headers } from "next/headers";
+import { isGenericEmail } from "../../is-generic-email";
+
+// Checks if SAML SSO is enforced for a given email domain
+export const isSamlEnforcedForEmailDomain = async (email: string) => {
+ const hostname = (await headers()).get("host");
+ const emailDomain = email.split("@")[1];
+
+ if (
+ !hostname ||
+ !emailDomain ||
+ !APP_HOSTNAMES.has(hostname) ||
+ isGenericEmail(email)
+ ) {
+ return false;
+ }
+
+ const workspace = await prisma.project.count({
+ where: {
+ ssoEmailDomain: emailDomain,
+ },
+ });
+
+ return workspace > 0;
+};
diff --git a/apps/web/lib/auth/options.ts b/apps/web/lib/auth/options.ts
index f1d7c453ad..69cb8adc65 100644
--- a/apps/web/lib/auth/options.ts
+++ b/apps/web/lib/auth/options.ts
@@ -7,7 +7,7 @@ import { sendEmail } from "@dub/email";
import LoginLink from "@dub/email/templates/login-link";
import { prisma } from "@dub/prisma";
import { PrismaClient } from "@dub/prisma/client";
-import { APP_DOMAIN_WITH_NGROK, APP_HOSTNAMES } from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { waitUntil } from "@vercel/functions";
import { User, type NextAuthOptions } from "next-auth";
@@ -17,10 +17,9 @@ import CredentialsProvider from "next-auth/providers/credentials";
import EmailProvider from "next-auth/providers/email";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";
-import { headers } from "next/headers";
import { createId } from "../api/create-id";
+import { isSamlEnforcedForEmailDomain } from "../api/workspaces/is-saml-enforced-for-email-domain";
import { qstash } from "../cron";
-import { isGenericEmail } from "../is-generic-email";
import { completeProgramApplications } from "../partners/complete-program-applications";
import { FRAMER_API_HOST } from "./constants";
import {
@@ -223,7 +222,7 @@ export const authOptions: NextAuthOptions = {
}
// SSO enforcement check
- const ssoEnforced = await isSamlEnforcedForDomain(email);
+ const ssoEnforced = await isSamlEnforcedForEmailDomain(email);
if (ssoEnforced) {
throw new Error("require-saml-sso");
@@ -349,7 +348,7 @@ export const authOptions: NextAuthOptions = {
account?.provider !== "saml-idp" &&
account?.provider !== "credentials" // for credentials, we do the check in the CredentialsProvider
) {
- const ssoEnforced = await isSamlEnforcedForDomain(user.email);
+ const ssoEnforced = await isSamlEnforcedForEmailDomain(user.email);
if (ssoEnforced) {
throw new Error("require-saml-sso");
@@ -610,33 +609,3 @@ export const authOptions: NextAuthOptions = {
},
},
};
-
-// Checks if SAML SSO is enforced for a given email domain
-export const isSamlEnforcedForDomain = async (email: string) => {
- const hostname = headers().get("host");
- const emailDomain = email.split("@")[1];
-
- if (
- !hostname ||
- !emailDomain ||
- !APP_HOSTNAMES.has(hostname) ||
- isGenericEmail(email)
- ) {
- return false;
- }
-
- const workspace = await prisma.project.findUnique({
- where: {
- ssoEmailDomain: emailDomain,
- },
- select: {
- ssoEnforcedAt: true,
- },
- });
-
- if (workspace?.ssoEnforcedAt) {
- return true;
- }
-
- return false;
-};
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 841619f8ac..0c1674b3b2 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -212,7 +212,6 @@ export interface ExtendedWorkspaceProps extends WorkspaceProps {
workspacePreferences?: z.infer<typeof workspacePreferencesSchema>;
})[];
publishableKey: string | null;
- ssoEnforcedAt: Date | null;
}
export type WorkspaceWithUsers = Omit<WorkspaceProps, "domains">;
diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.ts
index 9b966679e0..c31c91e028 100644
--- a/apps/web/lib/zod/schemas/workspaces.ts
+++ b/apps/web/lib/zod/schemas/workspaces.ts
@@ -167,7 +167,7 @@ export const WorkspaceSchemaExtended = WorkspaceSchema.extend({
}),
),
publishableKey: z.string().nullable(),
- ssoEnforcedAt: z.date().nullable(),
+ ssoEmailDomain: z.string().nullable(),
});
export const OnboardingUsageSchema = z.object({
diff --git a/packages/prisma/schema/workspace.prisma b/packages/prisma/schema/workspace.prisma
index 76fabd2f23..23ee074490 100644
--- a/packages/prisma/schema/workspace.prisma
+++ b/packages/prisma/schema/workspace.prisma
@@ -45,7 +45,6 @@ model Project {
webhookEnabled Boolean @default(false)
ssoEnabled Boolean @default(false) // TODO: this is not used
dotLinkClaimed Boolean @default(false)
- ssoEnforcedAt DateTime?
ssoEmailDomain String? @unique
createdAt DateTime @default(now())