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.

fixed some icky login welcome flow issues

Steven Teyb0eae40d2627
diff --git a/app/app/(auth)/login/form.tsx b/app/app/(auth)/login/form.tsx
index b01eb586dc..a73575be99 100644
--- a/app/app/(auth)/login/form.tsx
+++ b/app/app/(auth)/login/form.tsx
@@ -160,11 +160,6 @@ export default function LoginForm() {
placeholder="my-team"
autoComplete="off"
required
- value={email}
- onChange={(e) => {
- setNoSuchAccount(false);
- setEmail(e.target.value);
- }}
className="mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"
/>
</div>
diff --git a/components/app/links/link-filters.tsx b/components/app/links/link-filters.tsx
index 091cb21ade..548e7e5358 100644
--- a/components/app/links/link-filters.tsx
+++ b/components/app/links/link-filters.tsx
@@ -171,20 +171,19 @@ const DomainsFilter = ({ domains, primaryDomain }) => {
const [collapsed, setCollapsed] = useState(false);
- const options =
- domains.length === 0
+ const options = useMemo(() => {
+ return domains.length === 0
? [
{
- name: primaryDomain || "",
- value: primaryDomain || "",
+ value: primaryDomain.slug || "",
count: 0,
},
]
: domains.map(({ domain, _count }) => ({
- name: domain,
value: domain,
count: _count,
}));
+ }, [domains, primaryDomain]);
const { setShowAddEditDomainModal, setShowAddProjectModal } =
useContext(ModalContext);
@@ -225,7 +224,7 @@ const DomainsFilter = ({ domains, primaryDomain }) => {
className="mt-4 grid gap-2"
{...SWIPE_REVEAL_ANIMATION_SETTINGS}
>
- {options?.map(({ name, value, count }) => (
+ {options?.map(({ value, count }) => (
<div
key={value}
className="relative flex cursor-pointer items-center space-x-3 rounded-md bg-gray-50 transition-all hover:bg-gray-100"
@@ -248,7 +247,7 @@ const DomainsFilter = ({ domains, primaryDomain }) => {
htmlFor={value}
className="flex w-full cursor-pointer justify-between px-3 py-2 pl-0 text-sm font-medium text-gray-700"
>
- <p>{punycode.toUnicode(name || "")}</p>
+ <p>{punycode.toUnicode(value || "")}</p>
<p className="text-gray-500">{nFormatter(count)}</p>
</label>
</div>
diff --git a/components/app/modals/saml-modal.tsx b/components/app/modals/saml-modal.tsx
index 5826c76680..b31bf3315d 100644
--- a/components/app/modals/saml-modal.tsx
+++ b/components/app/modals/saml-modal.tsx
@@ -25,7 +25,7 @@ function SAMLModal({
const { slug } = useProject();
const [selectedProvider, setSelectedProvider] = useState<
SAMLProviderProps["saml"] | undefined
- >("okta");
+ >();
const [submitting, setSubmitting] = useState(false);
const { mutate } = useSAML();
@@ -85,7 +85,9 @@ function SAMLModal({
}
className="mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"
>
- <option disabled>Select a provider</option>
+ <option disabled selected>
+ Select a provider
+ </option>
{SAML_PROVIDERS.map((provider) => (
<option
key={provider.saml}
@@ -96,15 +98,25 @@ function SAMLModal({
</option>
))}
</select>
- <a
- href={`${HOME_DOMAIN}/help/article/${selectedProvider}-saml`}
- target="_blank"
- className="ml-2 mt-2 block text-sm text-gray-500 underline"
- >
- Read the guide on{" "}
- {SAML_PROVIDERS.find((p) => p.saml === selectedProvider)?.name}{" "}
- SSO
- </a>
+ {selectedProvider ? (
+ <a
+ href={`${HOME_DOMAIN}/help/article/${selectedProvider}-saml`}
+ target="_blank"
+ className="ml-2 mt-2 block text-sm text-gray-500 underline"
+ >
+ Read the guide on{" "}
+ {SAML_PROVIDERS.find((p) => p.saml === selectedProvider)?.name}{" "}
+ SSO
+ </a>
+ ) : (
+ <a
+ href={`${HOME_DOMAIN}/help/category/saml-sso`}
+ target="_blank"
+ className="ml-2 mt-2 block text-sm text-gray-500 underline"
+ >
+ Learn more about SAML SSO
+ </a>
+ )}
</div>
{(selectedProvider === "okta" || selectedProvider === "azure") && (
diff --git a/components/app/modals/scim-modal.tsx b/components/app/modals/scim-modal.tsx
index 72498b43ed..e8edc33fa5 100644
--- a/components/app/modals/scim-modal.tsx
+++ b/components/app/modals/scim-modal.tsx
@@ -27,9 +27,9 @@ function SCIMModal({
const { slug } = useProject();
const [submitting, setSubmitting] = useState(false);
const { scim, provider, configured, mutate } = useSCIM();
- const [selectedProvider, setSelectedProvider] = useState(
- provider || "okta-scim-v2",
- );
+ const [selectedProvider, setSelectedProvider] = useState<
+ SAMLProviderProps["scim"] | undefined
+ >(provider || undefined);
const [copiedBaseUrl, setCopiedBaseUrl] = useState(false);
const [showBearerToken, setShowBearerToken] = useState(false);
const [copiedBearerToken, setCopiedBearerToken] = useState(false);
@@ -108,8 +108,12 @@ function SCIMModal({
content={
<SimpleTooltipContent
title="Your directory provider is the IDP you use to manage your users."
- cta="Read the guide."
- href={`${HOME_DOMAIN}/help/article/configuring-scim`}
+ cta={selectedProvider ? "Read the guide." : "Learn more."}
+ href={`${HOME_DOMAIN}/help/${
+ selectedProvider
+ ? `article/${currentProvider.saml}-scim`
+ : "category/saml-sso"
+ }`}
/>
}
/>
@@ -124,6 +128,9 @@ function SCIMModal({
}
className="mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"
>
+ <option disabled selected>
+ Select a provider
+ </option>
{SAML_PROVIDERS.map((provider) => (
<option
key={provider.scim}
@@ -238,7 +245,7 @@ function SCIMModal({
<Button
text="Save changes"
loading={submitting}
- disabled={selectedProvider === provider}
+ disabled={selectedProvider && selectedProvider === provider}
/>
</form>
</div>
diff --git a/lib/middleware/app.ts b/lib/middleware/app.ts
index 854823c8de..c5e0ed0976 100644
--- a/lib/middleware/app.ts
+++ b/lib/middleware/app.ts
@@ -29,12 +29,12 @@ export default async function AppMiddleware(req: NextRequest) {
// if there's a session
} else if (session?.email) {
- // if the user was created in the last 10s and the path isn't /welcome, redirect to /welcome
+ // if the user was created in the last 10s
// (this is a workaround because the `isNewUser` flag is triggered when a user does `dangerousEmailAccountLinking`)
if (
session?.user?.createdAt &&
new Date(session?.user?.createdAt).getTime() > Date.now() - 10000 &&
- path !== "/welcome"
+ path === "/"
) {
// check if the user has an existing project invite, if yes, we skip the onboarding flow
const existingInvite = await conn
@@ -43,7 +43,23 @@ export default async function AppMiddleware(req: NextRequest) {
])
.then((res) => res.rows[0] as { projectId: string } | undefined);
- if (!existingInvite) {
+ // if there's an existing invite
+ if (existingInvite) {
+ // get the project slug
+ const project = await conn
+ ?.execute("SELECT slug from Project WHERE id = ?", [
+ existingInvite.projectId,
+ ])
+ .then((res) => res.rows[0] as { slug: string } | undefined);
+
+ // redirect them to the project slug
+ if (project?.slug) {
+ return NextResponse.redirect(new URL(project.slug, req.url));
+ } else {
+ return NextResponse.redirect(new URL("/", req.url));
+ }
+ } else {
+ // if there's no existing invite, redirect to /welcome flow
return NextResponse.redirect(new URL("/welcome", req.url));
}
diff --git a/lib/swr/use-domains.ts b/lib/swr/use-domains.ts
index c16a920361..bf8ff2b7d9 100644
--- a/lib/swr/use-domains.ts
+++ b/lib/swr/use-domains.ts
@@ -37,7 +37,9 @@ export default function useDomains({ domain }: { domain?: string } = {}) {
return {
domains,
- primaryDomain: domains?.find((domain) => domain.primary)?.slug,
+ primaryDomain:
+ domains?.find((domain) => domain.primary)?.slug ||
+ (domains && domains[0]),
verified: domain
? // If a domain is passed, check if it's verified
domains?.find((d) => d.slug === domain)?.verified
diff --git a/lib/swr/use-projects.ts b/lib/swr/use-projects.ts
index cdf506dc27..0efc25e14a 100644
--- a/lib/swr/use-projects.ts
+++ b/lib/swr/use-projects.ts
@@ -14,7 +14,8 @@ export default function useProjects() {
return {
projects: projects?.map((project) => ({
...project,
- primaryDomain: project.domains.find((domain) => domain.primary),
+ primaryDomain:
+ project.domains.find((domain) => domain.primary) || project.domains[0],
})),
};
}
diff --git a/package.json b/package.json
index 7c1e51fb9f..dd89e74aaa 100644
--- a/package.json
+++ b/package.json
@@ -59,7 +59,7 @@
"lucide-react": "^0.263.1",
"ms": "^2.1.3",
"next": "^13.4.14-canary.2",
- "next-auth": "^4.22.3",
+ "next-auth": "^4.23.1",
"next-contentlayer": "^0.3.4",
"node-html-parser": "^6.1.4",
"nodemailer": "^6.9.3",
diff --git a/pages/api/auth/[...nextauth].tsx b/pages/api/auth/[...nextauth].tsx
index db95074d5a..de6a6cbada 100644
--- a/pages/api/auth/[...nextauth].tsx
+++ b/pages/api/auth/[...nextauth].tsx
@@ -5,7 +5,7 @@ import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { sendEmail } from "emails";
import LoginLink from "emails/login-link";
import WelcomeEmail from "emails/welcome-email";
-import NextAuth, { Profile, type NextAuthOptions, User } from "next-auth";
+import NextAuth, { type NextAuthOptions, User } from "next-auth";
import prisma from "#/lib/prisma";
import jackson from "#/lib/jackson";
import { isBlacklistedEmail } from "#/lib/edge-config";
@@ -52,12 +52,30 @@ export const authOptions: NextAuthOptions = {
params: { grant_type: "authorization_code" },
},
userinfo: `${process.env.NEXTAUTH_URL}/api/auth/saml/userinfo`,
- profile: (profile) => {
+ profile: async (profile) => {
+ let existingUser = await prisma.user.findUnique({
+ where: { email: profile.email },
+ });
+
+ // user is authorized but doesn't have a Dub account, create one for them
+ if (!existingUser) {
+ existingUser = await prisma.user.create({
+ data: {
+ email: profile.email,
+ name: `${profile.firstName || ""} ${
+ profile.lastName || ""
+ }`.trim(),
+ },
+ });
+ }
+
+ const { id, name, email, image } = existingUser;
+
return {
- id: profile.id || "",
- email: profile.email || "",
- name: `${profile.firstName || ""} ${profile.lastName || ""}`.trim(),
- email_verified: true,
+ id,
+ name,
+ email,
+ image,
};
},
options: {
@@ -105,14 +123,20 @@ export const authOptions: NextAuthOptions = {
return null;
}
- const existingUser = await prisma.user.findUnique({
+ let existingUser = await prisma.user.findUnique({
where: { email: userInfo.email },
});
- // user is authorized but doesn't have a Dub account, prompt them to create one
+ // user is authorized but doesn't have a Dub account, create one for them
if (!existingUser) {
- console.log("NO SUCH USER, PROMPT TO CREATE");
- return null;
+ existingUser = await prisma.user.create({
+ data: {
+ email: userInfo.email,
+ name: `${userInfo.firstName || ""} ${
+ userInfo.lastName || ""
+ }`.trim(),
+ },
+ });
}
const { id, name, email, image } = existingUser;
@@ -173,6 +197,7 @@ export const authOptions: NextAuthOptions = {
account?.provider === "saml" ||
account?.provider === "saml-idp"
) {
+ console.log({ user, account, profile });
let samlProfile;
if (account?.provider === "saml-idp") {
@@ -224,7 +249,11 @@ export const authOptions: NextAuthOptions = {
const refreshedUser = await prisma.user.findUnique({
where: { id: token.sub },
});
- token.user = refreshedUser;
+ if (refreshedUser) {
+ token.user = refreshedUser;
+ } else {
+ return {};
+ }
}
return token;
diff --git a/yarn.lock b/yarn.lock
index 379ed01d62..84429c3055 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -8236,10 +8236,10 @@ negotiator@^0.6.3:
resolved "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz"
integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==
-next-auth@^4.22.3:
- version "4.22.3"
- resolved "https://registry.yarnpkg.com/next-auth/-/next-auth-4.22.3.tgz#bbe5152e0e3ea6d625731f23adba4fd2e3d2d570"
- integrity sha512-XAgy9xV3J2eJOXrQhmxdjV6MLM29ibm6WtMXc3KY6IPZeApf+SuBuPvlqCUfbu5YsAzlg9WSw6u01dChTfeZOA==
+next-auth@^4.23.1:
+ version "4.23.1"
+ resolved "https://registry.yarnpkg.com/next-auth/-/next-auth-4.23.1.tgz#7a82f5327cf4c7e32819da4eb977f2251a23c3cf"
+ integrity sha512-mL083z8KgRtlrIV6CDca2H1kduWJuK/3pTS0Fe2og15KOm4v2kkLGdSDfc2g+019aEBrJUT0pPW2Xx42ImN1WA==
dependencies:
"@babel/runtime" "^7.20.13"
"@panva/hkdf" "^1.0.2"