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.

wip

Kiran K3cfdf186deaf
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsx
new file mode 100644
index 0000000000..fc06c254b1
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import { useAddEditTokenModal } from "@/ui/modals/add-edit-token-modal";
+import { useDeleteTokenModal } from "@/ui/modals/delete-token-modal";
+import { useTokenCreatedModal } from "@/ui/modals/token-created-modal";
+import { IconMenu, LoadingSpinner, Popover, TokenAvatar } from "@dub/ui";
+import { fetcher, timeAgo } from "@dub/utils";
+import { Token } from "@prisma/client";
+import { FolderOpen, MoreVertical, Trash } from "lucide-react";
+import { useState } from "react";
+import useSWR from "swr";
+
+export default function TokensPageClient() {
+ const { data: tokens, isLoading } = useSWR<Token[]>(
+ "/api/user/tokens",
+ fetcher,
+ );
+
+ const [createdToken, setCreatedToken] = useState<string | null>(null);
+
+ const { AddEditTokenModal, setShowAddEditTokenModal, AddTokenButton } =
+ useAddEditTokenModal();
+ const { TokenCreatedModal, setShowTokenCreatedModal } = useTokenCreatedModal({
+ token: createdToken || "",
+ });
+
+ return (
+ <>
+ <TokenCreatedModal />
+ <AddEditTokenModal />
+ <div className="rounded-lg border border-gray-200 bg-white">
+ <div className="flex flex-col items-center justify-between gap-2 space-y-3 p-5 sm:flex-row sm:space-y-0 sm:p-10">
+ <div className="flex flex-col space-y-3">
+ <h2 className="text-xl font-medium">Workspace API Keys</h2>
+ <p className="text-sm text-gray-500">
+ These API keys allow other apps to access your workspace. Use it
+ with caution – do not share your API key with others, or expose it
+ in the browser or other client-side code
+ </p>
+ </div>
+ <div className="flex">
+ <AddTokenButton />
+ </div>
+ </div>
+ {isLoading || !tokens ? (
+ <div className="flex flex-col items-center justify-center space-y-4 pb-20 pt-10">
+ <LoadingSpinner className="h-6 w-6 text-gray-500" />
+ <p className="text-sm text-gray-500">Fetching API keys...</p>
+ </div>
+ ) : tokens.length > 0 ? (
+ <div>
+ <div className="grid grid-cols-5 border-b border-gray-200 px-5 py-2 text-sm font-medium text-gray-500 sm:px-10">
+ <div className="col-span-3">Name</div>
+ <div>Key</div>
+ <div className="text-center">Last used</div>
+ </div>
+ <div className="divide-y divide-gray-200">
+ {tokens.map((token) => (
+ <TokenRow key={token.id} {...token} />
+ ))}
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col items-center justify-center space-y-4 pb-20 pt-10">
+ <FolderOpen className="h-6 w-6 text-gray-500" />
+ <p className="text-sm text-gray-500">
+ No API keys found. Create one above.
+ </p>
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
+
+const TokenRow = (token: Token) => {
+ const [openPopover, setOpenPopover] = useState(false);
+ const { DeleteTokenModal, setShowDeleteTokenModal } = useDeleteTokenModal({
+ token,
+ });
+ return (
+ <>
+ <DeleteTokenModal />
+ <div className="relative grid grid-cols-5 items-center px-5 py-3 sm:px-10">
+ <div className="col-span-3 flex items-center space-x-3">
+ <TokenAvatar id={token.id} />
+ <div className="flex flex-col space-y-px">
+ <p className="font-semibold text-gray-700">{token.name}</p>
+ <p className="text-sm text-gray-500" suppressHydrationWarning>
+ Created {timeAgo(token.createdAt, { withAgo: true })}
+ </p>
+ </div>
+ </div>
+ <div className="font-mono text-sm">{token.partialKey}</div>
+ <div
+ className="text-center text-sm text-gray-500"
+ suppressHydrationWarning
+ >
+ {timeAgo(token.lastUsed)}
+ </div>
+ <Popover
+ content={
+ <div className="grid w-full gap-1 p-2 sm:w-48">
+ <button
+ onClick={() => {
+ setOpenPopover(false);
+ setShowDeleteTokenModal(true);
+ }}
+ className="rounded-md p-2 text-left text-sm font-medium text-red-600 transition-all duration-75 hover:bg-red-600 hover:text-white"
+ >
+ <IconMenu
+ text="Delete API Key"
+ icon={<Trash className="h-4 w-4" />}
+ />
+ </button>
+ </div>
+ }
+ align="end"
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ <button
+ onClick={() => {
+ setOpenPopover(!openPopover);
+ }}
+ className="absolute right-4 rounded-md px-1 py-2 transition-all duration-75 hover:bg-gray-100 active:bg-gray-200"
+ >
+ <MoreVertical className="h-5 w-5 text-gray-500" />
+ </button>
+ </Popover>
+ </div>
+ </>
+ );
+};
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page.tsx
new file mode 100644
index 0000000000..1ac838426c
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page.tsx
@@ -0,0 +1,5 @@
+import TokensPageClient from "./page-client";
+
+export default function TokensPage() {
+ return <TokensPageClient />;
+}
diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index dd985bf8e7..a87bed4759 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -40,16 +40,18 @@ interface ScopeDescription {
export const scopeDescriptions = [
{
- name: "Workspaces",
+ resource: "Workspaces",
description: "Read workspaces",
endpoints: ["/workspaces"],
permissions: [
{
+ permission: "Read",
scope: "workspaces.read",
description: "Read workspaces",
roles: ["owner", "member"],
},
{
+ permission: "Write",
scope: "workspaces.write",
description: "Write workspaces",
roles: ["owner"],
@@ -57,16 +59,18 @@ export const scopeDescriptions = [
],
},
{
- name: "Links",
+ resource: "Links",
description: "Create, read, update, and delete links",
endpoints: ["/links"],
permissions: [
{
+ permission: "Read",
scope: "links.read",
description: "Read links",
roles: ["owner", "member"],
},
{
+ permission: "Write",
scope: "links.write",
description: "Write links",
roles: ["owner", "member"],
@@ -74,16 +78,18 @@ export const scopeDescriptions = [
],
},
{
- name: "Tags",
+ resource: "Tags",
description: "Create, read, update, and delete tags",
endpoints: ["/tags"],
permissions: [
{
+ permission: "Read",
scope: "tags.read",
description: "Read tags",
roles: ["owner", "member"],
},
{
+ permission: "Write",
scope: "tags.write",
description: "Write tags",
roles: ["owner", "member"],
@@ -91,11 +97,12 @@ export const scopeDescriptions = [
],
},
{
- name: "Analytics",
+ resource: "Analytics",
description: "Read analytics",
endpoints: ["/analytics"],
permissions: [
{
+ permission: "Read",
scope: "analytics.read",
description: "Read analytics",
roles: ["owner", "member"],
@@ -103,16 +110,18 @@ export const scopeDescriptions = [
],
},
{
- name: "Domains",
+ resource: "Domains",
description: "Create, read, update, and delete domains",
endpoints: ["/domains"],
permissions: [
{
+ permission: "Read",
scope: "domains.read",
description: "Read domains",
roles: ["owner", "member"],
},
{
+ permission: "Write",
scope: "domains.write",
description: "Write domains",
roles: ["owner"],
diff --git a/apps/web/ui/modals/add-edit-token-modal/domain-input.tsx b/apps/web/ui/modals/add-edit-token-modal/domain-input.tsx
new file mode 100644
index 0000000000..055e62e429
--- /dev/null
+++ b/apps/web/ui/modals/add-edit-token-modal/domain-input.tsx
@@ -0,0 +1,188 @@
+import { AlertCircleFill, CheckCircleFill } from "@/ui/shared/icons";
+import { Label, RadioGroup, RadioGroupItem, useMediaQuery } from "@dub/ui";
+import { InfoTooltip } from "@dub/ui/src/tooltip";
+import {
+ FADE_IN_ANIMATION_SETTINGS,
+ cn,
+ getApexDomain,
+ getSubdomain,
+ getUrlFromString,
+} from "@dub/utils";
+import { motion } from "framer-motion";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useDebounce } from "use-debounce";
+
+export default function DomainInput({
+ identifier = "domain", // "domain" is the default, but when it's used in AddEditDomainModal, it's "slug"
+ data,
+ setData,
+ domainError,
+ setDomainError,
+}) {
+ const domain = data[identifier];
+ const originalDomain = useMemo(() => domain, []);
+ const [debouncedDomain] = useDebounce(domain, 500);
+
+ useEffect(() => {
+ if (
+ debouncedDomain.length > 0 &&
+ debouncedDomain.toLowerCase() !== originalDomain.toLowerCase()
+ ) {
+ fetch(`/api/domains/${domain}/exists`).then(async (res) => {
+ const exists = await res.json();
+ setDomainError(exists === 1 ? "Domain is already in use." : null);
+ });
+ }
+ }, [debouncedDomain]);
+
+ const [domainType, setDomainType] = useState<string | undefined>(undefined);
+ const apexDomain = useMemo(
+ () => getApexDomain(getUrlFromString(domain)),
+ [domain],
+ );
+
+ const { isMobile } = useMediaQuery();
+ const domainRef = useRef<HTMLInputElement>(null);
+ const subdomainRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ if (domainType === "website") {
+ subdomainRef.current?.focus();
+ }
+ }, [domainType]);
+
+ return (
+ <>
+ <div className="relative mt-2 flex rounded-md shadow-sm">
+ {domainType === "website" ? (
+ <div className="relative flex w-full rounded-md shadow-sm">
+ <input
+ ref={subdomainRef}
+ name="subdomain"
+ id="subdomain"
+ type="text"
+ required
+ autoComplete="off"
+ placeholder="subdomain"
+ className="w-1/3 rounded-l-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ value={getSubdomain(domain, apexDomain) || ""}
+ onChange={(e) => {
+ setData({
+ ...data,
+ [identifier]: `${e.target.value}.${apexDomain}`,
+ });
+ }}
+ aria-invalid="true"
+ />
+ <span className="inline-flex flex-1 items-center rounded-r-md border border-l-0 border-gray-300 bg-gray-50 px-3 text-gray-500 sm:text-sm">
+ .{apexDomain}
+ </span>
+ </div>
+ ) : (
+ <input
+ ref={domainRef}
+ name="domain"
+ id="domain"
+ type="text"
+ required
+ autoFocus={!isMobile && identifier === "slug"}
+ autoComplete="off"
+ pattern="[a-zA-Z0-9\-.]+"
+ className={cn(
+ "block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm",
+ {
+ "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500":
+ domainError,
+ },
+ )}
+ placeholder="go.acme.com"
+ value={domain}
+ onChange={(e) => {
+ setDomainError(null);
+ setData({ ...data, [identifier]: e.target.value });
+ }}
+ aria-invalid="true"
+ />
+ )}
+ {domainError ? (
+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
+ <AlertCircleFill
+ className="h-5 w-5 text-red-500"
+ aria-hidden="true"
+ />
+ </div>
+ ) : domainType === "spare" ? (
+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
+ <CheckCircleFill
+ className="h-5 w-5 text-green-500"
+ aria-hidden="true"
+ />
+ </div>
+ ) : null}
+ </div>
+ {domainError &&
+ (domainError === "Domain is already in use." ? (
+ <p className="mt-2 text-sm text-red-600" id="domain-error">
+ Domain is already in use.{" "}
+ <a
+ className="underline"
+ href="mailto:[email protected]?subject=My Domain Is Already In Use"
+ >
+ Contact us
+ </a>{" "}
+ if you'd like to use this domain for your workspace.
+ </p>
+ ) : (
+ <p className="mt-2 text-sm text-red-600" id="domain-error">
+ {domainError}
+ </p>
+ ))}
+ {domain && !domainError && (
+ <motion.div {...FADE_IN_ANIMATION_SETTINGS}>
+ <RadioGroup
+ className="mt-2"
+ name="domainType"
+ required
+ value={domainType}
+ onValueChange={(value) => {
+ setDomainType(value);
+ }}
+ >
+ <div className="flex items-center space-x-2 rounded-md border border-gray-300 bg-white transition-all hover:bg-gray-50 active:bg-gray-100">
+ <RadioGroupItem value="spare" id="spare" className="ml-3" />
+ <Label
+ htmlFor="spare"
+ className="flex flex-1 cursor-pointer items-center justify-between space-x-1 p-3 pl-0"
+ >
+ <p className="text-gray-600">This is a spare domain</p>
+ <InfoTooltip content="If this is a separate domain that you're planning to use solely for short links, then you're good to go." />
+ </Label>
+ </div>
+ <div className="flex items-center space-x-2 rounded-md border border-gray-300 bg-white transition-all hover:bg-gray-50 active:bg-gray-100">
+ <RadioGroupItem value="website" id="website" className="ml-3" />
+ <Label
+ htmlFor="website"
+ className="flex flex-1 cursor-pointer items-center justify-between space-x-1 p-3 pl-0"
+ >
+ <p className="text-gray-600">This is our website's domain</p>
+ <InfoTooltip content="If you're using this domain for your main website or app, you should be using a subdomain for your short links instead (e.g. go.acme.com)." />
+ </Label>
+ </div>
+ </RadioGroup>
+ </motion.div>
+ )}
+ {(domain.includes("/") || domainType === "website") && (
+ <p className="mt-2 text-sm text-gray-500">
+ Want to set up Dub.co to handle redirects on a subpath instead?{" "}
+ <a
+ href="https://dub.co/help/article/how-to-use-dub-with-subpath"
+ target="_blank"
+ className="underline"
+ >
+ Read this guide.
+ </a>
+ </p>
+ )}
+ </>
+ );
+}
diff --git a/apps/web/ui/modals/add-edit-token-modal/index.tsx b/apps/web/ui/modals/add-edit-token-modal/index.tsx
new file mode 100644
index 0000000000..8e7a8a6225
--- /dev/null
+++ b/apps/web/ui/modals/add-edit-token-modal/index.tsx
@@ -0,0 +1,255 @@
+import { scopeDescriptions as allScopes } from "@/lib/api/tokens/scopes";
+import useWorkspace from "@/lib/swr/use-workspace";
+import {
+ BlurImage,
+ Button,
+ ButtonProps,
+ Logo,
+ Modal,
+ Toggle,
+ useRouterStuff,
+} from "@dub/ui";
+import { useParams, useRouter } from "next/navigation";
+import {
+ Dispatch,
+ FormEvent,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+
+// TODO:
+// Fetch the scopes from the API
+
+type APIKeyProps = {
+ id?: string;
+ name: string;
+ scopes: string[];
+ isMachine: boolean;
+};
+
+function AddEditTokenModal({
+ showAddEditTokenModal,
+ setShowAddEditTokenModal,
+ props,
+}: {
+ showAddEditTokenModal: boolean;
+ setShowAddEditTokenModal: Dispatch<SetStateAction<boolean>>;
+ props?: APIKeyProps;
+}) {
+ const router = useRouter();
+ const { slug } = useParams() as { slug: string };
+ const { id, logo, plan } = useWorkspace();
+ const { queryParams } = useRouterStuff();
+
+ const [saving, setSaving] = useState(false);
+ const [lockDomain, setLockDomain] = useState(true);
+ const [domainError, setDomainError] = useState<string | null>(null);
+ const [expanded, setExpanded] = useState(false);
+ const [data, setData] = useState<APIKeyProps>(
+ props || {
+ id: "",
+ name: "",
+ scopes: [],
+ isMachine: false,
+ },
+ );
+
+ const saveDisabled = useMemo(() => {
+ /*
+ Disable save if:
+ - modal is not open
+ - saving is in progress
+ - domain is invalid
+ - for an existing domain, there's no changes
+ */
+ if (
+ !showAddEditTokenModal ||
+ saving ||
+ domainError ||
+ (props &&
+ Object.entries(props).every(([key, value]) => data[key] === value))
+ ) {
+ return true;
+ } else {
+ return false;
+ }
+ }, [showAddEditTokenModal, saving, domainError, props, data]);
+
+ const endpoint = useMemo(() => {
+ if (props) {
+ return {
+ method: "PATCH",
+ url: `/api/domains/${"domain"}?workspaceId=${id}`,
+ successMessage: "Successfully updated domain!",
+ };
+ } else {
+ return {
+ method: "POST",
+ url: `/api/domains?workspaceId=${id}`,
+ successMessage: "Successfully added domain!",
+ };
+ }
+ }, [props]);
+
+ const { name, scopes, isMachine } = data;
+
+ // Save the form data
+ const onSubmit = (e: FormEvent) => {
+ e.preventDefault();
+ setSaving(true);
+ };
+
+ return (
+ <Modal
+ showModal={showAddEditTokenModal}
+ setShowModal={setShowAddEditTokenModal}
+ className="scrollbar-hide h-fit max-h-[95vh] overflow-auto"
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">
+ {logo ? (
+ <BlurImage
+ src={logo}
+ alt={`Logo for ${slug}`}
+ className="h-10 w-10 rounded-full border border-gray-200"
+ width={20}
+ height={20}
+ />
+ ) : (
+ <Logo />
+ )}
+ <h1 className="text-lg font-medium">
+ {props ? "Edit" : "Add"} API Key
+ </h1>
+ </div>
+
+ <form
+ onSubmit={onSubmit}
+ className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-10"
+ >
+ <div>
+ <label htmlFor="name" className="flex items-center space-x-2">
+ <h2 className="text-sm font-medium text-gray-900">Name</h2>
+ </label>
+ <div className="relative mt-2 rounded-md shadow-sm">
+ <input
+ name="target"
+ id="target"
+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ placeholder="My Test Key"
+ value={name}
+ onChange={(e) => setData({ ...data, name: e.target.value })}
+ />
+ </div>
+ </div>
+
+ {/* This is the format we should display the scopes in the modal:
+ Links -> None, Read, Write
+ - /api/links
+ - /api/links/:id
+ Tags -> None, Read, Write
+ - /api/tags
+ - /api/tags/:id */}
+
+ {/* <div className="font-sm flex justify-between text-sm text-gray-500">
+ <div>Resources</div>
+ <div>Permissions</div>
+ </div> */}
+
+ <div className="flex flex-col space-y-3 text-sm text-gray-900">
+ {allScopes.map((scope) => (
+ <div className="flex items-center justify-between">
+ <div>{scope.resource}</div>
+ <div>
+ <Toggle size="sm" aria-label="Toggle italic">
+ None
+ </Toggle>
+ {scope.permissions.map((permission) => (
+ <Toggle size="sm" aria-label="Toggle italic">
+ {permission.permission}
+ </Toggle>
+ ))}
+
+ {/* <select
+ name="scopes"
+ id={`scopes-${scope.resource}`}
+ className="block w-40 rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ value={scopes[0]}
+ onChange={(e) =>
+ setData({
+ ...data,
+ scopes: [e.target.value, scopes[1]],
+ })
+ }
+ >
+ <option value="none">None</option>
+ <option value="read">Read</option>
+ <option value="write">Write</option>
+ </select> */}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ <Button
+ text={props ? "Save changes" : "Create API key"}
+ disabled={saveDisabled}
+ loading={saving}
+ />
+ </form>
+ </Modal>
+ );
+}
+
+function AddTokenButton({
+ setShowAddEditTokenModal,
+ buttonProps,
+}: {
+ setShowAddEditTokenModal: Dispatch<SetStateAction<boolean>>;
+ buttonProps?: Partial<ButtonProps>;
+}) {
+ return (
+ <div>
+ <Button
+ text="New API Key"
+ onClick={() => setShowAddEditTokenModal(true)}
+ className="w-36"
+ {...buttonProps}
+ />
+ </div>
+ );
+}
+
+export function useAddEditTokenModal({ props }: { props?: APIKeyProps } = {}) {
+ const [showAddEditTokenModal, setShowAddEditTokenModal] = useState(false);
+
+ const AddEditTokenModalCallback = useCallback(() => {
+ return (
+ <AddEditTokenModal
+ showAddEditTokenModal={showAddEditTokenModal}
+ setShowAddEditTokenModal={setShowAddEditTokenModal}
+ props={props}
+ />
+ );
+ }, [showAddEditTokenModal, setShowAddEditTokenModal]);
+
+ const AddTokenButtonCallback = useCallback(() => {
+ return (
+ <AddTokenButton setShowAddEditTokenModal={setShowAddEditTokenModal} />
+ );
+ }, [setShowAddEditTokenModal]);
+
+ return useMemo(
+ () => ({
+ setShowAddEditTokenModal,
+ AddEditTokenModal: AddEditTokenModalCallback,
+ AddTokenButton: AddTokenButtonCallback,
+ }),
+ [
+ setShowAddEditTokenModal,
+ AddEditTokenModalCallback,
+ AddTokenButtonCallback,
+ ],
+ );
+}