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 design for delete-token-modal

Kiran K138d25b3f0e5
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
deleted file mode 100644
index 594def8783..0000000000
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/tokens/page-client-old.tsx
+++ /dev/null
@@ -1,224 +0,0 @@
-"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 c824c74b27..0552e2b39d 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
@@ -53,7 +53,7 @@ export default function TokensPageClient() {
const { table, ...tableProps } = useTable({
data: tokens || [],
- loading: isLoading,
+ loading: isLoading && !error && !tokens,
error: error ? "Failed to fetch tokens." : undefined,
columns: [
{
@@ -143,6 +143,8 @@ export default function TokensPageClient() {
<div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
</>
)}
+ addButton={<AddTokenButton />}
+ learnMoreHref="https://dub.co/docs/api-reference/tokens"
/>
),
resourceName: (plural) => `token${plural ? "s" : ""}`,
@@ -176,7 +178,7 @@ export default function TokensPageClient() {
<AddTokenButton />
</div>
- {isLoading || tokens?.length ? (
+ {tokens?.length !== 0 ? (
<Table
{...tableProps}
table={table}
diff --git a/apps/web/ui/modals/add-edit-token-modal-old.tsx b/apps/web/ui/modals/add-edit-token-modal-old.tsx
deleted file mode 100644
index d20c0b2d61..0000000000
--- a/apps/web/ui/modals/add-edit-token-modal-old.tsx
+++ /dev/null
@@ -1,410 +0,0 @@
-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/delete-token-modal.tsx b/apps/web/ui/modals/delete-token-modal.tsx
index c5ce564787..1f7aa86a5c 100644
--- a/apps/web/ui/modals/delete-token-modal.tsx
+++ b/apps/web/ui/modals/delete-token-modal.tsx
@@ -1,7 +1,7 @@
import useWorkspace from "@/lib/swr/use-workspace";
import { TokenProps } from "@/lib/types";
-import { Badge, Button, Modal, TokenAvatar, useMediaQuery } from "@dub/ui";
-import { timeAgo } from "@dub/utils";
+import { Button, Key, Modal, Tooltip, useMediaQuery } from "@dub/ui";
+import { DICEBEAR_AVATAR_URL } from "@dub/utils";
import {
Dispatch,
SetStateAction,
@@ -57,20 +57,40 @@ function DeleteTokenModal({
</div>
<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}
- </Badge>
- <TokenAvatar id={token.id} />
- <div className="flex flex-col">
- <h3 className="line-clamp-1 w-48 font-semibold text-gray-700">
+ <div className="relative flex items-center gap-2 space-x-3 rounded-md border border-gray-300 bg-white px-4 py-2">
+ <Key className="size-5 text-gray-500" />
+
+ <div className="flex flex-1 flex-col gap-0.5">
+ <h3 className="line-clamp-1 font-medium text-neutral-600">
{token.name}
</h3>
- <p className="text-xs text-gray-500" suppressHydrationWarning>
- Last used {timeAgo(token.lastUsed, { withAgo: true })}
+ <p
+ className="text-xs font-medium text-neutral-500"
+ suppressHydrationWarning
+ >
+ {token.partialKey}
+ </p>
+ </div>
+
+ <div className="flex items-center gap-2">
+ <Tooltip content={token.user.name}>
+ <img
+ src={
+ token.user.image || `${DICEBEAR_AVATAR_URL}${token.user.id}`
+ }
+ alt={token.user.name!}
+ className="size-5 rounded-full"
+ />
+ </Tooltip>
+ <p>
+ {new Date(token.createdAt).toLocaleDateString("en-us", {
+ month: "short",
+ day: "numeric",
+ })}
</p>
</div>
</div>
+
<Button
text="Delete"
variant="danger"