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.

New API key design

Kiran Kf6377edb368c
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/page-client.tsx
index aa97f583b7..8370f7f018 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/library/tags/page-client.tsx
@@ -2,7 +2,6 @@
import useTags from "@/lib/swr/use-tags";
import useTagsCount from "@/lib/swr/use-tags-count";
-import useWorkspace from "@/lib/swr/use-workspace";
import { TAGS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/tags";
import { useAddEditTagModal } from "@/ui/modals/add-edit-tag-modal";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
@@ -28,7 +27,6 @@ export const TagsListContext = createContext<{
export default function WorkspaceTagsClient() {
const { searchParams, queryParams } = useRouterStuff();
- const { id: workspaceId } = useWorkspace();
const { AddEditTagModal, AddTagButton } = useAddEditTagModal();
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client-old.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client-old.tsx
new file mode 100644
index 0000000000..594def8783
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client-old.tsx
@@ -0,0 +1,224 @@
+"use client";
+
+import { scopesToName } from "@/lib/api/tokens/scopes";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { TokenProps } from "@/lib/types";
+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 EmptyState from "@/ui/shared/empty-state";
+import { Delete } from "@/ui/shared/icons";
+import {
+ Avatar,
+ Badge,
+ Button,
+ LoadingSpinner,
+ Popover,
+ TokenAvatar,
+ Tooltip,
+} from "@dub/ui";
+import { Key } from "@dub/ui/icons";
+import { fetcher, timeAgo } from "@dub/utils";
+import { Edit3, MoreVertical } from "lucide-react";
+import { useState } from "react";
+import useSWR from "swr";
+
+export default function TokensPageClient() {
+ const { id: workspaceId } = useWorkspace();
+ const { data: tokens, isLoading } = useSWR<TokenProps[]>(
+ `/api/tokens?workspaceId=${workspaceId}`,
+ fetcher,
+ );
+
+ const [createdToken, setCreatedToken] = useState<string | null>(null);
+ const { TokenCreatedModal, setShowTokenCreatedModal } = useTokenCreatedModal({
+ token: createdToken || "",
+ });
+
+ const onTokenCreated = (token: string) => {
+ setCreatedToken(token);
+ setShowTokenCreatedModal(true);
+ };
+
+ const { AddEditTokenModal, AddTokenButton } = useAddEditTokenModal({
+ onTokenCreated,
+ });
+
+ return (
+ <>
+ <TokenCreatedModal />
+ <AddEditTokenModal />
+ <div className="rounded-lg border border-gray-200 bg-white">
+ <div className="flex flex-col items-center justify-between gap-4 space-y-3 border-b border-gray-200 p-5 sm:flex-row sm:space-y-0 sm:p-10">
+ <div className="flex max-w-screen-sm flex-col space-y-3">
+ <h2 className="text-xl font-medium">Secret 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.{" "}
+ <a
+ href="https://dub.co/docs/api-reference/tokens"
+ target="_blank"
+ className="font-medium underline underline-offset-4 hover:text-black"
+ >
+ Learn more
+ </a>
+ </p>
+ </div>
+ <AddTokenButton />
+ </div>
+ {isLoading || !tokens ? (
+ <div className="flex flex-col items-center justify-center space-y-4 py-20">
+ <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="hidden grid-cols-5 border-b border-gray-200 px-5 py-2 text-sm font-medium text-gray-500 sm:grid 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 gap-y-4 py-20">
+ <EmptyState
+ icon={Key}
+ title="No API keys found for this workspace"
+ />
+ <AddTokenButton />
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
+
+const TokenRow = (token: TokenProps) => {
+ const [openPopover, setOpenPopover] = useState(false);
+
+ const { setShowAddEditTokenModal, AddEditTokenModal } = useAddEditTokenModal({
+ token: {
+ id: token.id,
+ name: token.name,
+ isMachine: token.user.isMachine,
+ scopes: mapScopesToResource(token.scopes),
+ },
+ });
+
+ const { DeleteTokenModal, setShowDeleteTokenModal } = useDeleteTokenModal({
+ token,
+ });
+
+ return (
+ <>
+ <AddEditTokenModal />
+ <DeleteTokenModal />
+ <div className="relative flex flex-col gap-2 px-5 py-3 sm:grid sm:grid-cols-5 sm:items-center sm:px-10">
+ <div className="col-span-3 flex flex-col gap-3 sm:flex-row sm:items-center">
+ <TokenAvatar id={token.id} />
+ <div className="flex flex-col gap-y-px">
+ <div className="flex items-center gap-x-2">
+ <p className="font-semibold text-gray-700">{token.name}</p>
+ <Badge variant="neutral">{scopesToName(token.scopes).name}</Badge>
+ </div>
+ <div className="flex items-center gap-x-1">
+ <Tooltip
+ content={
+ <div className="w-full max-w-xs p-4">
+ <Avatar user={token.user} className="h-10 w-10" />
+ <div className="mt-2 flex items-center gap-x-1.5">
+ <p className="text-sm font-semibold text-gray-700">
+ {token.user.name || "Anonymous User"}
+ </p>
+ </div>
+ <p className="mt-1 text-xs text-gray-500">
+ Created{" "}
+ {new Date(token.createdAt).toLocaleDateString("en-us", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })}
+ </p>
+ </div>
+ }
+ >
+ <div>
+ <Avatar user={token.user} className="h-4 w-4" />
+ </div>
+ </Tooltip>
+ <p>•</p>
+ <p className="text-sm text-gray-500" suppressHydrationWarning>
+ Created {timeAgo(token.createdAt)}
+ </p>
+ </div>
+ </div>
+ </div>
+ <div className="font-mono text-sm">{token.partialKey}</div>
+ <div
+ className="text-sm text-gray-500 sm:text-center"
+ suppressHydrationWarning
+ >
+ {timeAgo(token.lastUsed)}
+ </div>
+ <Popover
+ content={
+ <div className="w-full sm:w-48">
+ <div className="grid gap-px p-2">
+ <Button
+ text="Edit API Key"
+ variant="outline"
+ icon={<Edit3 className="h-4 w-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ onClick={() => {
+ setOpenPopover(false);
+ setShowAddEditTokenModal(true);
+ }}
+ />
+ <Button
+ text="Delete API Key"
+ variant="danger-outline"
+ icon={<Delete className="h-4 w-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ onClick={() => {
+ setOpenPopover(false);
+ setShowDeleteTokenModal(true);
+ }}
+ />
+ </div>
+ </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>
+ </>
+ );
+};
+
+const mapScopesToResource = (scopes: string[]) => {
+ const result = scopes.map((scope) => {
+ const [resource] = scope.split(".");
+
+ return {
+ [resource]: scope,
+ };
+ });
+
+ return Object.assign({}, ...result);
+};
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
index 594def8783..c824c74b27 100644
--- 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
@@ -6,31 +6,38 @@ import { TokenProps } from "@/lib/types";
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 EmptyState from "@/ui/shared/empty-state";
+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { Delete } from "@/ui/shared/icons";
import {
- Avatar,
- Badge,
Button,
- LoadingSpinner,
+ Dots,
+ Icon,
+ Key,
+ PenWriting,
Popover,
- TokenAvatar,
+ Table,
Tooltip,
+ usePagination,
+ useTable,
} from "@dub/ui";
-import { Key } from "@dub/ui/icons";
-import { fetcher, timeAgo } from "@dub/utils";
-import { Edit3, MoreVertical } from "lucide-react";
+import { cn, DICEBEAR_AVATAR_URL, fetcher, timeAgo } from "@dub/utils";
+import { Command } from "cmdk";
import { useState } from "react";
import useSWR from "swr";
export default function TokensPageClient() {
const { id: workspaceId } = useWorkspace();
- const { data: tokens, isLoading } = useSWR<TokenProps[]>(
- `/api/tokens?workspaceId=${workspaceId}`,
- fetcher,
- );
+ const {
+ data: tokens,
+ isLoading,
+ error,
+ } = useSWR<TokenProps[]>(`/api/tokens?workspaceId=${workspaceId}`, fetcher);
+
+ const limit = tokens?.length || 0;
+ const { pagination, setPagination } = usePagination(limit);
const [createdToken, setCreatedToken] = useState<string | null>(null);
+
const { TokenCreatedModal, setShowTokenCreatedModal } = useTokenCreatedModal({
token: createdToken || "",
});
@@ -44,63 +51,156 @@ export default function TokensPageClient() {
onTokenCreated,
});
+ const { table, ...tableProps } = useTable({
+ data: tokens || [],
+ loading: isLoading,
+ error: error ? "Failed to fetch tokens." : undefined,
+ columns: [
+ {
+ id: "name",
+ header: "Name",
+ accessorKey: "name",
+ cell: ({ row }) => {
+ return (
+ <span className="flex items-center gap-2">
+ <Key className="size-4 text-gray-500" />
+ {row.original.name}
+ </span>
+ );
+ },
+ },
+ {
+ id: "permissions",
+ header: "Permissions",
+ accessorKey: "scopes",
+ cell: ({ row }) => scopesToName(row.original.scopes).name,
+ },
+ {
+ id: "user",
+ header: "Created",
+ accessorKey: "user",
+ cell: ({ row }) => {
+ return (
+ <div className="flex items-center gap-2">
+ <Tooltip content={row.original.user.name}>
+ <img
+ src={
+ row.original.user.image ||
+ `${DICEBEAR_AVATAR_URL}${row.original.user.id}`
+ }
+ alt={row.original.user.name!}
+ className="size-5 rounded-full"
+ />
+ </Tooltip>
+ <p>
+ {new Date(row.original.createdAt).toLocaleDateString("en-us", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })}
+ </p>
+ </div>
+ );
+ },
+ },
+ {
+ id: "partialKey",
+ header: "Key",
+ accessorKey: "partialKey",
+ cell: ({ row }) => row.original.partialKey,
+ },
+ {
+ id: "lastUsed",
+ header: "Last used",
+ accessorKey: "lastUsed",
+ cell: ({ row }) => timeAgo(row.original.lastUsed),
+ },
+
+ // Menu
+ {
+ id: "menu",
+ enableHiding: false,
+ minSize: 43,
+ size: 43,
+ maxSize: 43,
+ cell: ({ row }) => <RowMenuButton token={row.original} />,
+ },
+ ],
+ ...(!limit && {
+ pagination,
+ onPaginationChange: setPagination,
+ }),
+ rowCount: tokens?.length || 0,
+ thClassName: "border-l-0",
+ tdClassName: "border-l-0",
+ emptyState: (
+ <AnimatedEmptyState
+ title="No tokens found"
+ description="No tokens have been created for this workspace yet."
+ cardContent={() => (
+ <>
+ <Key className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ </>
+ )}
+ />
+ ),
+ resourceName: (plural) => `token${plural ? "s" : ""}`,
+ });
+
return (
<>
<TokenCreatedModal />
<AddEditTokenModal />
- <div className="rounded-lg border border-gray-200 bg-white">
- <div className="flex flex-col items-center justify-between gap-4 space-y-3 border-b border-gray-200 p-5 sm:flex-row sm:space-y-0 sm:p-10">
- <div className="flex max-w-screen-sm flex-col space-y-3">
- <h2 className="text-xl font-medium">Secret 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.{" "}
- <a
- href="https://dub.co/docs/api-reference/tokens"
- target="_blank"
- className="font-medium underline underline-offset-4 hover:text-black"
- >
- Learn more
- </a>
- </p>
- </div>
+
+ <div>
+ <h1 className="text-2xl font-semibold tracking-tight text-black">
+ Secret keys
+ </h1>
+ <p className="mb-2 mt-2 text-base text-neutral-600">
+ 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.{" "}
+ <a
+ href="https://dub.co/docs/api-reference/tokens"
+ target="_blank"
+ className="font-medium underline underline-offset-4 hover:text-black"
+ >
+ Learn more
+ </a>
+ </p>
+ </div>
+
+ <div className="grid gap-4 pb-10">
+ <div className="flex w-full items-center justify-end">
<AddTokenButton />
</div>
- {isLoading || !tokens ? (
- <div className="flex flex-col items-center justify-center space-y-4 py-20">
- <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="hidden grid-cols-5 border-b border-gray-200 px-5 py-2 text-sm font-medium text-gray-500 sm:grid 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>
+
+ {isLoading || tokens?.length ? (
+ <Table
+ {...tableProps}
+ table={table}
+ containerClassName="border-neutral-300"
+ />
) : (
- <div className="flex flex-col items-center justify-center gap-y-4 py-20">
- <EmptyState
- icon={Key}
- title="No API keys found for this workspace"
- />
- <AddTokenButton />
- </div>
+ <AnimatedEmptyState
+ title="No tokens found"
+ description="No tokens have been created for this workspace yet."
+ cardContent={() => (
+ <>
+ <Key className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ </>
+ )}
+ />
)}
</div>
</>
);
}
-const TokenRow = (token: TokenProps) => {
- const [openPopover, setOpenPopover] = useState(false);
+function RowMenuButton({ token }: { token: TokenProps }) {
+ const [isOpen, setIsOpen] = useState(false);
const { setShowAddEditTokenModal, AddEditTokenModal } = useAddEditTokenModal({
token: {
@@ -119,97 +219,69 @@ const TokenRow = (token: TokenProps) => {
<>
<AddEditTokenModal />
<DeleteTokenModal />
- <div className="relative flex flex-col gap-2 px-5 py-3 sm:grid sm:grid-cols-5 sm:items-center sm:px-10">
- <div className="col-span-3 flex flex-col gap-3 sm:flex-row sm:items-center">
- <TokenAvatar id={token.id} />
- <div className="flex flex-col gap-y-px">
- <div className="flex items-center gap-x-2">
- <p className="font-semibold text-gray-700">{token.name}</p>
- <Badge variant="neutral">{scopesToName(token.scopes).name}</Badge>
- </div>
- <div className="flex items-center gap-x-1">
- <Tooltip
- content={
- <div className="w-full max-w-xs p-4">
- <Avatar user={token.user} className="h-10 w-10" />
- <div className="mt-2 flex items-center gap-x-1.5">
- <p className="text-sm font-semibold text-gray-700">
- {token.user.name || "Anonymous User"}
- </p>
- </div>
- <p className="mt-1 text-xs text-gray-500">
- Created{" "}
- {new Date(token.createdAt).toLocaleDateString("en-us", {
- month: "short",
- day: "numeric",
- year: "numeric",
- })}
- </p>
- </div>
- }
- >
- <div>
- <Avatar user={token.user} className="h-4 w-4" />
- </div>
- </Tooltip>
- <p>•</p>
- <p className="text-sm text-gray-500" suppressHydrationWarning>
- Created {timeAgo(token.createdAt)}
- </p>
- </div>
- </div>
- </div>
- <div className="font-mono text-sm">{token.partialKey}</div>
- <div
- className="text-sm text-gray-500 sm:text-center"
- suppressHydrationWarning
- >
- {timeAgo(token.lastUsed)}
- </div>
- <Popover
- content={
- <div className="w-full sm:w-48">
- <div className="grid gap-px p-2">
- <Button
- text="Edit API Key"
- variant="outline"
- icon={<Edit3 className="h-4 w-4" />}
- className="h-9 justify-start px-2 font-medium"
- onClick={() => {
- setOpenPopover(false);
- setShowAddEditTokenModal(true);
- }}
- />
- <Button
- text="Delete API Key"
- variant="danger-outline"
- icon={<Delete className="h-4 w-4" />}
- className="h-9 justify-start px-2 font-medium"
- onClick={() => {
- setOpenPopover(false);
- setShowDeleteTokenModal(true);
- }}
- />
- </div>
- </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>
+ <Popover
+ openPopover={isOpen}
+ setOpenPopover={setIsOpen}
+ content={
+ <Command tabIndex={0} loop className="focus:outline-none">
+ <Command.List className="flex w-screen flex-col gap-1 p-1.5 text-sm sm:w-auto sm:min-w-[130px]">
+ <MenuItem
+ icon={PenWriting}
+ label="Edit"
+ onSelect={() => {
+ setIsOpen(false);
+ setShowAddEditTokenModal(true);
+ }}
+ />
+
+ <MenuItem
+ icon={Delete}
+ label="Delete"
+ onSelect={() => {
+ setIsOpen(false);
+ setShowDeleteTokenModal(true);
+ }}
+ />
+ </Command.List>
+ </Command>
+ }
+ align="end"
+ >
+ <Button
+ type="button"
+ className="h-8 whitespace-nowrap px-2"
+ variant="outline"
+ icon={<Dots className="h-4 w-4 shrink-0" />}
+ />
+ </Popover>
</>
);
-};
+}
+
+function MenuItem({
+ icon: IconComp,
+ label,
+ onSelect,
+ variant,
+}: {
+ icon: Icon;
+ label: string;
+ onSelect: () => void;
+ variant?: string;
+}) {
+ return (
+ <Command.Item
+ className={cn(
+ "flex cursor-pointer select-none items-center gap-2 whitespace-nowrap rounded-md p-2 text-sm text-neutral-600",
+ "data-[selected=true]:bg-gray-100",
+ )}
+ onSelect={onSelect}
+ >
+ <IconComp className="size-4 shrink-0 text-neutral-500" />
+ {label}
+ </Command.Item>
+ );
+}
const mapScopesToResource = (scopes: string[]) => {
const result = scopes.map((scope) => {
diff --git a/apps/web/ui/modals/add-edit-token-modal-old.tsx b/apps/web/ui/modals/add-edit-token-modal-old.tsx
new file mode 100644
index 0000000000..d20c0b2d61
--- /dev/null
+++ b/apps/web/ui/modals/add-edit-token-modal-old.tsx
@@ -0,0 +1,410 @@
+import { ResourceKey, RESOURCES } from "@/lib/api/rbac/resources";
+import {
+ getScopesByResourceForRole,
+ Scope,
+ scopePresets,
+} from "@/lib/api/tokens/scopes";
+import useWorkspace from "@/lib/swr/use-workspace";
+import {
+ AnimatedSizeContainer,
+ BlurImage,
+ Button,
+ ButtonProps,
+ InfoTooltip,
+ Label,
+ Logo,
+ Modal,
+ RadioGroup,
+ RadioGroupItem,
+ SimpleTooltipContent,
+ ToggleGroup,
+} from "@dub/ui";
+import { cn } from "@dub/utils";
+import {
+ Dispatch,
+ FormEvent,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import { toast } from "sonner";
+import { mutate } from "swr";
+
+type APIKeyProps = {
+ id?: string;
+ name: string;
+ scopes: { [key: string]: Scope };
+ isMachine: boolean;
+};
+
+type ScopePreset = "all_access" | "read_only" | "restricted";
+
+const newToken: APIKeyProps = {
+ name: "",
+ scopes: { api: "apis.all" },
+ isMachine: false,
+};
+
+function AddEditTokenModal({
+ showAddEditTokenModal,
+ setShowAddEditTokenModal,
+ token,
+ onTokenCreated,
+}: {
+ showAddEditTokenModal: boolean;
+ setShowAddEditTokenModal: Dispatch<SetStateAction<boolean>>;
+ token?: APIKeyProps;
+ onTokenCreated?: (token: string) => void;
+}) {
+ const [saving, setSaving] = useState(false);
+ const {
+ id: workspaceId,
+ logo,
+ slug,
+ role,
+ isOwner,
+ conversionEnabled,
+ } = useWorkspace();
+ const [data, setData] = useState<APIKeyProps>(token || newToken);
+ const [preset, setPreset] = useState<ScopePreset>("all_access");
+
+ useEffect(() => {
+ if (!token) return;
+
+ const scopes = Object.values(token.scopes);
+
+ if (scopes.includes("apis.all")) {
+ setPreset("all_access");
+ } else if (scopes.includes("apis.read")) {
+ setPreset("read_only");
+ } else {
+ setPreset("restricted");
+ }
+ }, [token]);
+
+ // Determine the endpoint
+ const endpoint = useMemo(() => {
+ if (token) {
+ return {
+ method: "PATCH",
+ url: `/api/tokens/${token.id}?workspaceId=${workspaceId}`,
+ successMessage: "API key updated!",
+ };
+ } else {
+ return {
+ method: "POST",
+ url: `/api/tokens?workspaceId=${workspaceId}`,
+ successMessage: "API key created!",
+ };
+ }
+ }, [token]);
+
+ // Save the form data
+ const onSubmit = async (e: FormEvent) => {
+ e.preventDefault();
+ setSaving(true);
+
+ const response = await fetch(endpoint.url, {
+ method: endpoint.method,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ ...data,
+ scopes: Object.values(scopes).filter((v) => v),
+ }),
+ });
+
+ const result = await response.json();
+
+ if (response.ok) {
+ mutate(`/api/tokens?workspaceId=${workspaceId}`);
+ toast.success(endpoint.successMessage);
+ onTokenCreated?.(result.token);
+ setShowAddEditTokenModal(false);
+ } else {
+ toast.error(result.error.message);
+ }
+ };
+
+ const { name, scopes } = data;
+ const buttonDisabled =
+ (!name || token?.name === name) && token?.scopes === scopes;
+
+ const scopesByResources = useMemo(
+ () =>
+ transformScopesForUI(getScopesByResourceForRole(role)).filter(
+ ({ key }) => key !== "conversions" || conversionEnabled,
+ ),
+ [role, conversionEnabled],
+ );
+
+ return (
+ <>
+ <Modal
+ showModal={showAddEditTokenModal}
+ setShowModal={setShowAddEditTokenModal}
+ className="max-h-[95dvh]"
+ >
+ <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">
+ {token ? "Edit" : "Add New"} API Key
+ </h1>
+ </div>
+
+ <form
+ onSubmit={onSubmit}
+ className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 text-left sm:px-10"
+ >
+ {/* Can't change the type of the token */}
+ {!token && (
+ <div>
+ <RadioGroup
+ className="flex"
+ defaultValue="user"
+ required
+ onValueChange={(value) =>
+ setData({ ...data, isMachine: value === "machine" })
+ }
+ >
+ <div className="flex w-1/2 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="user" id="user" className="ml-3" />
+ <Label
+ htmlFor="user"
+ className="flex flex-1 cursor-pointer items-center justify-between space-x-1 p-3 pl-0"
+ >
+ <p className="text-gray-600">You</p>
+ <InfoTooltip
+ content={
+ <SimpleTooltipContent
+ title="This API key will be tied to your user account – if you are removed from the workspace, it will be deleted."
+ cta="Learn more"
+ href="https://dub.co/docs/api-reference/tokens"
+ />
+ }
+ />
+ </Label>
+ </div>
+ <div
+ className={cn(
+ "flex w-1/2 items-center space-x-2 rounded-md border border-gray-300 bg-white transition-all hover:bg-gray-50 active:bg-gray-100",
+ {
+ "cursor-not-allowed opacity-75": !isOwner,
+ },
+ )}
+ >
+ <RadioGroupItem
+ value="machine"
+ id="machine"
+ className="ml-3"
+ disabled={!isOwner}
+ />
+ <Label
+ htmlFor="machine"
+ className={cn(
+ "flex flex-1 cursor-pointer items-center justify-between space-x-1 p-3 pl-0",
+ {
+ "cursor-not-allowed": !isOwner,
+ },
+ )}
+ >
+ <p className="text-gray-600">Machine</p>
+ <InfoTooltip
+ content={
+ <SimpleTooltipContent
+ title={
+ isOwner
+ ? "A new bot member will be added to your workspace, and the key will be associated with it. Since the key is not tied to your account, it will not be deleted even if you leave the workspace."
+ : "Only the workspace owner can create machine users."
+ }
+ cta="Learn more"
+ href="https://dub.co/docs/api-reference/tokens#machine-users"
+ />
+ }
+ />
+ </Label>
+ </div>
+ </RadioGroup>
+ </div>
+ )}
+
+ <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
+ 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"
+ required
+ value={name}
+ onChange={(e) => setData({ ...data, name: e.target.value })}
+ autoFocus
+ autoComplete="off"
+ />
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <h2 className="text-sm font-medium text-gray-900">Permissions</h2>
+ <div className="flex">
+ <ToggleGroup
+ options={scopePresets}
+ selected={preset}
+ selectAction={(value: ScopePreset) => {
+ setPreset(value);
+
+ if (value === "all_access") {
+ setData({ ...data, scopes: { api: "apis.all" } });
+ } else if (value === "read_only") {
+ setData({ ...data, scopes: { api: "apis.read" } });
+ } else {
+ setData({ ...data, scopes: {} });
+ }
+ }}
+ />
+ </div>
+ </div>
+
+ <AnimatedSizeContainer height>
+ <div className="p-1 pt-0 text-sm text-gray-500">
+ This API key will have{" "}
+ {scopePresets.find((p) => p.value === preset)?.description}
+ </div>
+ {preset === "restricted" && (
+ <div className="flex flex-col divide-y text-sm">
+ {scopesByResources.map((resource) => (
+ <div
+ className="flex items-center justify-between py-4"
+ key={resource.key}
+ >
+ <div className="flex items-center gap-1.5 text-gray-500">
+ <p>{resource.name}</p>
+ <InfoTooltip content={resource.description} />
+ </div>
+ <div>
+ <RadioGroup
+ defaultValue={scopes[resource.key] || ""}
+ className="flex gap-4"
+ onValueChange={(v: Scope) => {
+ setData({
+ ...data,
+ scopes: {
+ ...scopes,
+ [resource.key]: v,
+ },
+ });
+ }}
+ >
+ <div className="flex items-center space-x-2">
+ <RadioGroupItem value="" />
+ <div>None</div>
+ </div>
+ {resource.scopes.map((scope) => (
+ <div
+ className="flex items-center space-x-2"
+ key={scope.scope}
+ >
+ <RadioGroupItem value={scope.scope} />
+ <div className="capitalize">{scope.type}</div>
+ </div>
+ ))}
+ </RadioGroup>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </AnimatedSizeContainer>
+
+ <Button
+ text={token ? "Save changes" : "Create API key"}
+ disabled={buttonDisabled}
+ loading={saving}
+ />
+ </form>
+ </Modal>
+ </>
+ );
+}
+
+function AddTokenButton({
+ setShowAddEditTokenModal,
+ buttonProps,
+}: {
+ setShowAddEditTokenModal: Dispatch<SetStateAction<boolean>>;
+ buttonProps?: Partial<ButtonProps>;
+}) {
+ return (
+ <div>
+ <Button
+ text="Create API key"
+ onClick={() => setShowAddEditTokenModal(true)}
+ {...buttonProps}
+ />
+ </div>
+ );
+}
+
+export function useAddEditTokenModal(
+ {
+ token,
+ onTokenCreated,
+ }: {
+ token?: APIKeyProps;
+ onTokenCreated?: (token: string) => void;
+ } = { onTokenCreated: () => {} },
+) {
+ const [showAddEditTokenModal, setShowAddEditTokenModal] = useState(false);
+
+ const AddEditTokenModalCallback = useCallback(() => {
+ return (
+ <AddEditTokenModal
+ showAddEditTokenModal={showAddEditTokenModal}
+ setShowAddEditTokenModal={setShowAddEditTokenModal}
+ token={token}
+ onTokenCreated={onTokenCreated}
+ />
+ );
+ }, [showAddEditTokenModal, setShowAddEditTokenModal]);
+
+ const AddTokenButtonCallback = useCallback(() => {
+ return (
+ <AddTokenButton setShowAddEditTokenModal={setShowAddEditTokenModal} />
+ );
+ }, [setShowAddEditTokenModal]);
+
+ return useMemo(
+ () => ({
+ setShowAddEditTokenModal,
+ AddEditTokenModal: AddEditTokenModalCallback,
+ AddTokenButton: AddTokenButtonCallback,
+ }),
+ [
+ setShowAddEditTokenModal,
+ AddEditTokenModalCallback,
+ AddTokenButtonCallback,
+ ],
+ );
+}
+
+const transformScopesForUI = (scopedResources) => {
+ return Object.keys(scopedResources).map((resourceKey: ResourceKey) => {
+ return {
+ ...RESOURCES.find((r) => r.key === resourceKey)!,
+ scopes: scopedResources[resourceKey],
+ };
+ });
+};
diff --git a/apps/web/ui/modals/add-edit-token-modal.tsx b/apps/web/ui/modals/add-edit-token-modal.tsx
index 03b44cdc35..827115981e 100644
--- a/apps/web/ui/modals/add-edit-token-modal.tsx
+++ b/apps/web/ui/modals/add-edit-token-modal.tsx
@@ -7,19 +7,15 @@ import {
import useWorkspace from "@/lib/swr/use-workspace";
import {
AnimatedSizeContainer,
- BlurImage,
Button,
ButtonProps,
InfoTooltip,
- Label,
- Logo,
Modal,
RadioGroup,
RadioGroupItem,
SimpleTooltipContent,
ToggleGroup,
} from "@dub/ui";
-import { cn } from "@dub/utils";
import {
Dispatch,
FormEvent,
@@ -59,19 +55,14 @@ function AddEditTokenModal({
onTokenCreated?: (token: string) => void;
}) {
const [saving, setSaving] = useState(false);
- const {
- id: workspaceId,
- logo,
- slug,
- role,
- isOwner,
- conversionEnabled,
- } = useWorkspace();
+ const { id: workspaceId, role, isOwner, conversionEnabled } = useWorkspace();
const [data, setData] = useState<APIKeyProps>(token || newToken);
const [preset, setPreset] = useState<ScopePreset>("all_access");
useEffect(() => {
- if (!token) return;
+ if (!token) {
+ return;
+ }
const scopes = Object.values(token.scopes);
@@ -141,103 +132,78 @@ function AddEditTokenModal({
[role, conversionEnabled],
);
+ const helpTexts = {
+ user: {
+ title:
+ "This API key will be tied to your user account – if you are removed from the workspace, it will be deleted.",
+ cta: "Learn more",
+ href: "https://dub.co/docs/api-reference/tokens",
+ },
+ machine: {
+ title: isOwner
+ ? "A new bot member will be added to your workspace, and the key will be associated with it. Since the key is not tied to your account, it will not be deleted even if you leave the workspace."
+ : "Only the workspace owner can create machine users.",
+ cta: "Learn more",
+ href: "https://dub.co/docs/api-reference/tokens#machine-users",
+ },
+ };
+
+ const helpText = helpTexts[data.isMachine ? "machine" : "user"];
+
return (
<>
<Modal
showModal={showAddEditTokenModal}
setShowModal={setShowAddEditTokenModal}
- className="max-h-[95dvh]"
+ className="max-w-lg"
>
- <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">
- {token ? "Edit" : "Add New"} API Key
- </h1>
- </div>
+ <h3 className="border-b border-neutral-200 px-4 py-4 text-lg font-medium sm:px-6">
+ {token ? "Edit" : "Create New"} API Key
+ </h3>
<form
onSubmit={onSubmit}
- className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 text-left sm:px-10"
+ className="flex flex-col space-y-4 bg-neutral-50 px-4 py-8 text-left sm:px-10"
>
{/* Can't change the type of the token */}
{!token && (
- <div>
- <RadioGroup
- className="flex"
- defaultValue="user"
- required
- onValueChange={(value) =>
- setData({ ...data, isMachine: value === "machine" })
- }
- >
- <div className="flex w-1/2 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="user" id="user" className="ml-3" />
- <Label
- htmlFor="user"
- className="flex flex-1 cursor-pointer items-center justify-between space-x-1 p-3 pl-0"
- >
- <p className="text-gray-600">You</p>
- <InfoTooltip
- content={
- <SimpleTooltipContent
- title="This API key will be tied to your user account – if you are removed from the workspace, it will be deleted."
- cta="Learn more"
- href="https://dub.co/docs/api-reference/tokens"
- />
- }
- />
- </Label>
- </div>
- <div
- className={cn(
- "flex w-1/2 items-center space-x-2 rounded-md border border-gray-300 bg-white transition-all hover:bg-gray-50 active:bg-gray-100",
- {
- "cursor-not-allowed opacity-75": !isOwner,
- },
- )}
- >
- <RadioGroupItem
- value="machine"
- id="machine"
- className="ml-3"
- disabled={!isOwner}
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <label htmlFor="domain" className="flex items-center gap-x-2">
+ <h2 className="text-sm font-medium text-neutral-700">
+ Member
+ </h2>
+ <InfoTooltip
+ content={
+ <SimpleTooltipContent
+ title={helpText.title}
+ cta={helpText.cta}
+ href={helpText.href}
+ />
+ }
/>
- <Label
- htmlFor="machine"
- className={cn(
- "flex flex-1 cursor-pointer items-center justify-between space-x-1 p-3 pl-0",
- {
- "cursor-not-allowed": !isOwner,
- },
- )}
- >
- <p className="text-gray-600">Machine</p>
- <InfoTooltip
- content={
- <SimpleTooltipContent
- title={
- isOwner
- ? "A new bot member will be added to your workspace, and the key will be associated with it. Since the key is not tied to your account, it will not be deleted even if you leave the workspace."
- : "Only the workspace owner can create machine users."
- }
- cta="Learn more"
- href="https://dub.co/docs/api-reference/tokens#machine-users"
- />
- }
- />
- </Label>
- </div>
- </RadioGroup>
+ </label>
+ </div>
+
+ <ToggleGroup
+ options={[
+ {
+ value: "user",
+ label: "You",
+ },
+ {
+ value: "machine",
+ label: "Machine",
+ },
+ ]}
+ selected={data.isMachine ? "machine" : "user"}
+ selectAction={(id: "machine" | "user") =>
+ setData({ ...data, isMachine: id === "machine" })
+ }
+ className="grid grid-cols-2 rounded-md border border-neutral-300 bg-neutral-100"
+ optionClassName="w-full h-8 flex items-center justify-center font-medium"
+ indicatorClassName="rounded-md bg-white border border-neutral-300 shadow-sm"
+ />
</div>
)}
@@ -258,24 +224,28 @@ function AddEditTokenModal({
</div>
<div className="flex flex-col gap-2">
- <h2 className="text-sm font-medium text-gray-900">Permissions</h2>
- <div className="flex">
- <ToggleGroup
- options={scopePresets}
- selected={preset}
- selectAction={(value: ScopePreset) => {
- setPreset(value);
+ <label htmlFor="domain" className="flex items-center gap-x-2">
+ <h2 className="text-sm font-medium text-gray-900">Permissions</h2>
+ </label>
- if (value === "all_access") {
- setData({ ...data, scopes: { api: "apis.all" } });
- } else if (value === "read_only") {
- setData({ ...data, scopes: { api: "apis.read" } });
- } else {
- setData({ ...data, scopes: {} });
- }
- }}
- />
- </div>
+ <ToggleGroup
+ options={scopePresets}
+ selected={preset}
+ selectAction={(value: ScopePreset) => {
+ setPreset(value);
+
+ if (value === "all_access") {
+ setData({ ...data, scopes: { api: "apis.all" } });
+ } else if (value === "read_only") {
+ setData({ ...data, scopes: { api: "apis.read" } });
+ } else {
+ setData({ ...data, scopes: {} });
+ }
+ }}
+ className="grid grid-cols-3 rounded-md border border-neutral-300 bg-neutral-100"
+ optionClassName="w-full h-8 flex items-center justify-center font-medium"
+ indicatorClassName="rounded-md bg-white border border-neutral-300 shadow-sm"
+ />
</div>
<AnimatedSizeContainer height>
@@ -290,8 +260,10 @@ function AddEditTokenModal({
className="flex items-center justify-between py-4"
key={resource.key}
>
- <div className="flex items-center gap-1.5 text-gray-500">
- <p>{resource.name}</p>
+ <div className="flex items-center gap-1.5">
+ <span className="text-sm font-medium text-neutral-800">
+ {resource.name}
+ </span>
<InfoTooltip content={resource.description} />
</div>
<div>
@@ -350,7 +322,7 @@ function AddTokenButton({
return (
<div>
<Button
- text="Create"
+ text="Create API key"
onClick={() => setShowAddEditTokenModal(true)}
{...buttonProps}
/>
diff --git a/apps/web/ui/modals/delete-token-modal.tsx b/apps/web/ui/modals/delete-token-modal.tsx
index d01497c65c..c5ce564787 100644
--- a/apps/web/ui/modals/delete-token-modal.tsx
+++ b/apps/web/ui/modals/delete-token-modal.tsx
@@ -1,13 +1,6 @@
import useWorkspace from "@/lib/swr/use-workspace";
import { TokenProps } from "@/lib/types";
-import {
- Badge,
- Button,
- Logo,
- Modal,
- TokenAvatar,
- useMediaQuery,
-} from "@dub/ui";
+import { Badge, Button, Modal, TokenAvatar, useMediaQuery } from "@dub/ui";
import { timeAgo } from "@dub/utils";
import {
Dispatch,
@@ -53,17 +46,17 @@ function DeleteTokenModal({
<Modal
showModal={showDeleteTokenModal}
setShowModal={setShowDeleteTokenModal}
+ className="max-w-md"
>
- <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 />
+ <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">
<h3 className="text-lg font-medium">Delete API Key</h3>
- <p className="text-center text-sm text-gray-500">
+ <p className="text-sm text-gray-500">
This will permanently delete the API key for and revoke all access to
your account. Are you sure you want to continue?
</p>
</div>
- <div className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 text-left sm:px-16">
+ <div className="flex flex-col space-y-4 bg-neutral-50 px-4 py-4 sm:px-6">
<div className="relative flex items-center space-x-3 rounded-md border border-gray-300 bg-white px-1 py-3">
<Badge variant="neutral" className="absolute right-2 top-2">
{token.partialKey}
@@ -79,7 +72,7 @@ function DeleteTokenModal({
</div>
</div>
<Button
- text="Confirm"
+ text="Delete"
variant="danger"
autoFocus={!isMobile}
loading={removing}
diff --git a/apps/web/ui/modals/token-created-modal.tsx b/apps/web/ui/modals/token-created-modal.tsx
index 5f3f335c02..85403a55b4 100644
--- a/apps/web/ui/modals/token-created-modal.tsx
+++ b/apps/web/ui/modals/token-created-modal.tsx
@@ -1,4 +1,4 @@
-import { Button, CopyButton, Logo, Modal } from "@dub/ui";
+import { Button, CopyButton, Modal } from "@dub/ui";
import {
Dispatch,
SetStateAction,
@@ -20,26 +20,25 @@ function TokenCreatedModal({
<Modal
showModal={showTokenCreatedModal}
setShowModal={setShowTokenCreatedModal}
+ className="max-w-md"
>
- <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 />
+ <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">
<h3 className="text-lg font-medium">API Key Created</h3>
- <p className="text-center text-sm text-gray-500">
+ <p className="text-sm text-gray-500">
For security reasons, we will only show you the key once. Please copy
and store it somewhere safe.
</p>
</div>
- <div className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 text-left sm:px-16">
- <div className="flex items-center justify-between rounded-md border border-gray-300 bg-white p-3">
- <p className="font-mono text-sm text-gray-500">{token}</p>
- <CopyButton value={token} className="rounded-md" />
+ <div className="flex flex-col space-y-4 bg-neutral-50 px-4 py-8 sm:px-6">
+ <div className="flex flex-col gap-1">
+ <h2 className="text-sm font-medium text-neutral-800">API key</h2>
+ <div className="flex items-center justify-between rounded-md border border-gray-300 bg-white p-3">
+ <p className="font-mono text-sm text-gray-500">{token}</p>
+ <CopyButton value={token} className="rounded-md" />
+ </div>
</div>
- <Button
- text="Done"
- variant="secondary"
- onClick={() => setShowTokenCreatedModal(false)}
- />
+ <Button text="Done" onClick={() => setShowTokenCreatedModal(false)} />
</div>
</Modal>
);