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.

edit token modal

Kiran K3c2cae514f71
diff --git a/apps/web/app/api/tokens/[id]/route.ts b/apps/web/app/api/tokens/[id]/route.ts
index 9ca423779c..8210918382 100644
--- a/apps/web/app/api/tokens/[id]/route.ts
+++ b/apps/web/app/api/tokens/[id]/route.ts
@@ -49,7 +49,9 @@ export const GET = withWorkspace(
// PATCH /api/tokens/:id - update a specific token
export const PATCH = withWorkspace(
async ({ workspace, params, req }) => {
- const { scopes } = updateTokenSchema.parse(await parseRequestBody(req));
+ const { name, scopes } = updateTokenSchema.parse(
+ await parseRequestBody(req),
+ );
const token = await prisma.restrictedToken.update({
where: {
@@ -57,6 +59,7 @@ export const PATCH = withWorkspace(
projectId: workspace.id,
},
data: {
+ name,
scopes: scopes.join(" "),
},
select: {
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 23f2dfd8de..c2abfd2928 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
@@ -1,20 +1,20 @@
"use client";
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 { Delete } from "@/ui/shared/icons";
import { Button, LoadingSpinner, Popover, TokenAvatar } from "@dub/ui";
import { fetcher, timeAgo } from "@dub/utils";
-import { Token } from "@prisma/client";
import { Edit3, FolderOpen, 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<Token[]>(
+ const { data: tokens, isLoading } = useSWR<TokenProps[]>(
`/api/tokens?workspaceId=${workspaceId}`,
fetcher,
);
@@ -84,15 +84,27 @@ export default function TokensPageClient() {
);
}
-const TokenRow = (token: Token) => {
+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),
+ },
+ onTokenCreated: () => {},
+ });
+
const { DeleteTokenModal, setShowDeleteTokenModal } = useDeleteTokenModal({
- token,
+ token: token as any, // TODO: Fix this
tokenType: "workspace",
});
return (
<>
+ <AddEditTokenModal />
<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">
@@ -120,10 +132,10 @@ const TokenRow = (token: Token) => {
variant="outline"
icon={<Edit3 className="h-4 w-4" />}
className="h-9 justify-start px-2 font-medium"
- // onClick={() => {
- // setOpenPopover(false);
- // setShowAddEditDomainModal(true);
- // }}
+ onClick={() => {
+ setOpenPopover(false);
+ setShowAddEditTokenModal(true);
+ }}
/>
<Button
text="Delete API Key"
@@ -155,3 +167,15 @@ const TokenRow = (token: Token) => {
</>
);
};
+
+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/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index 123c7eead7..79ad2e6511 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -41,6 +41,7 @@ interface ScopeDescription {
export const scopeDescriptions = [
{
resource: "Workspaces",
+ key: "workspaces",
description: "Read, update, and delete workspaces",
endpoints: ["/workspaces"],
permissions: [
@@ -60,6 +61,7 @@ export const scopeDescriptions = [
},
{
resource: "Links",
+ key: "links",
description: "Create, read, update, and delete links",
endpoints: ["/links"],
permissions: [
@@ -79,6 +81,7 @@ export const scopeDescriptions = [
},
{
resource: "Tags",
+ key: "tags",
description: "Create, read, update, and delete tags",
endpoints: ["/tags"],
permissions: [
@@ -98,6 +101,7 @@ export const scopeDescriptions = [
},
{
resource: "Domains",
+ key: "domains",
description: "Create, read, update, and delete domains",
endpoints: ["/domains"],
permissions: [
@@ -117,6 +121,7 @@ export const scopeDescriptions = [
},
{
resource: "API Keys",
+ key: "tokens",
description: "Create, read, update, and delete API keys",
endpoints: ["/tokens"],
permissions: [
@@ -136,6 +141,7 @@ export const scopeDescriptions = [
},
{
resource: "Analytics",
+ key: "analytics",
description: "Read analytics",
endpoints: ["/analytics"],
permissions: [
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 98fd74040c..b580927fcf 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -3,6 +3,7 @@ import { metaTagsSchema } from "@/lib/zod/schemas/metatags";
import { DirectorySyncProviders } from "@boxyhq/saml-jackson";
import { Link } from "@prisma/client";
import { createLinkBodySchema } from "./zod/schemas/links";
+import { tokenSchema } from "./zod/schemas/token";
export type LinkProps = Link;
@@ -196,4 +197,6 @@ export const tagColors = [
"brown",
] as const;
-export type MetaTag = z.infer<typeof metaTagsSchema>;
\ No newline at end of file
+export type MetaTag = z.infer<typeof metaTagsSchema>;
+
+export type TokenProps = z.infer<typeof tokenSchema>;
\ No newline at end of file
diff --git a/apps/web/lib/zod/schemas/token.ts b/apps/web/lib/zod/schemas/token.ts
index d6e8fc14a7..4593c9fd3c 100644
--- a/apps/web/lib/zod/schemas/token.ts
+++ b/apps/web/lib/zod/schemas/token.ts
@@ -16,6 +16,7 @@ export const createTokenSchema = z.object({
// Schema to validate the request body when updating a token
export const updateTokenSchema = createTokenSchema
.pick({
+ name: true,
scopes: true,
})
.required();
diff --git a/apps/web/ui/modals/add-edit-token-modal/index.tsx b/apps/web/ui/modals/add-edit-token-modal/index.tsx
index 59f710f8dc..d1007ef6f1 100644
--- a/apps/web/ui/modals/add-edit-token-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-token-modal/index.tsx
@@ -22,9 +22,6 @@ import {
import { toast } from "sonner";
import { mutate } from "swr";
-// TODO:
-// Fetch the scopes from the API
-
type APIKeyProps = {
id?: string;
name: string;
@@ -41,24 +38,24 @@ const newToken: APIKeyProps = {
function AddEditTokenModal({
showAddEditTokenModal,
setShowAddEditTokenModal,
- props,
+ token,
onTokenCreated,
}: {
showAddEditTokenModal: boolean;
setShowAddEditTokenModal: Dispatch<SetStateAction<boolean>>;
- props?: APIKeyProps;
- onTokenCreated: (token: string) => void;
+ token?: APIKeyProps;
+ onTokenCreated?: (token: string) => void;
}) {
const [saving, setSaving] = useState(false);
const { id: workspaceId, logo, slug } = useWorkspace();
- const [data, setData] = useState<APIKeyProps>(props || newToken);
+ const [data, setData] = useState<APIKeyProps>(token || newToken);
// Determine the endpoint
const endpoint = useMemo(() => {
- if (props) {
+ if (token) {
return {
method: "PATCH",
- url: `/api/tokens/${"id"}?workspaceId=${workspaceId}`,
+ url: `/api/tokens/${token.id}?workspaceId=${workspaceId}`,
successMessage: "API key updated!",
};
} else {
@@ -68,7 +65,7 @@ function AddEditTokenModal({
successMessage: "API key created!",
};
}
- }, [props]);
+ }, [token]);
// Save the form data
const onSubmit = async (e: FormEvent) => {
@@ -91,15 +88,16 @@ function AddEditTokenModal({
if (response.ok) {
mutate(`/api/tokens?workspaceId=${workspaceId}`);
toast.success(endpoint.successMessage);
- onTokenCreated(result.token);
+ onTokenCreated?.(result.token);
setShowAddEditTokenModal(false);
} else {
toast.error(result.error.message);
}
};
- const { name, scopes, isMachine } = data;
- const buttonDisabled = !name;
+ const { name, scopes } = data;
+ const buttonDisabled =
+ (!name || token?.name === name) && token?.scopes === scopes;
return (
<>
@@ -121,7 +119,7 @@ function AddEditTokenModal({
<Logo />
)}
<h1 className="text-lg font-medium">
- {props ? "Edit" : "Add New"} API Key
+ {token ? "Edit" : "Add New"} API Key
</h1>
</div>
@@ -129,37 +127,44 @@ function AddEditTokenModal({
onSubmit={onSubmit}
className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 text-left sm:px-10"
>
- <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="This API key is tied to your user and can make requests against the selected workspace. If you are removed from the workspace, this key will be disabled." />
- </Label>
- </div>
- <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="machine" id="machine" className="ml-3" />
- <Label
- htmlFor="machine"
- className="flex flex-1 cursor-pointer items-center justify-between space-x-1 p-3 pl-0"
- >
- <p className="text-gray-600">Machine</p>
- <InfoTooltip content="A new bot member will be added to your workspace, and an API key will be created. Since this are not tied to a user, you can enusre that API key remains active even if you leave the workspace." />
- </Label>
- </div>
- </RadioGroup>
- </div>
+ {/* 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="This API key is tied to your user and can make requests against the selected workspace. If you are removed from the workspace, this key will be disabled." />
+ </Label>
+ </div>
+ <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="machine"
+ id="machine"
+ className="ml-3"
+ />
+ <Label
+ htmlFor="machine"
+ className="flex flex-1 cursor-pointer items-center justify-between space-x-1 p-3 pl-0"
+ >
+ <p className="text-gray-600">Machine</p>
+ <InfoTooltip content="A new bot member will be added to your workspace, and an API key will be created. Since this are not tied to a user, you can enusre that API key remains active even if you leave the workspace." />
+ </Label>
+ </div>
+ </RadioGroup>
+ </div>
+ )}
<div>
<label htmlFor="name" className="flex items-center space-x-2">
@@ -167,27 +172,25 @@ function AddEditTokenModal({
</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"
required
value={name}
onChange={(e) => setData({ ...data, name: e.target.value })}
+ autoFocus
/>
</div>
</div>
<span className="text-sm text-gray-500">
- Choose the permissions for this API key. These permissions apply
- when the API key is used to make requests to Dub.
+ These permissions apply when the API key is used to make requests to
+ Dub APIs.
</span>
<div className="flex flex-col divide-y text-sm">
{allScopes.map((scope) => (
<div
className="flex items-center justify-between py-4"
- key={`${scope.resource}-resource`}
+ key={scope.key}
>
<div className="flex gap-1 text-gray-500">
<p>{scope.resource}</p>
@@ -195,14 +198,14 @@ function AddEditTokenModal({
</div>
<div>
<RadioGroup
- defaultValue=""
+ defaultValue={scopes[scope.key] || ""}
className="flex gap-4"
onValueChange={(v) => {
setData({
...data,
scopes: {
...scopes,
- [scope.resource.toLocaleLowerCase()]: v,
+ [scope.key]: v,
},
});
}}
@@ -227,7 +230,7 @@ function AddEditTokenModal({
</div>
<Button
- text={props ? "Save changes" : "Create API key"}
+ text={token ? "Save changes" : "Create API key"}
disabled={buttonDisabled}
loading={saving}
/>
@@ -258,11 +261,11 @@ function AddTokenButton({
export function useAddEditTokenModal(
{
- props,
+ token,
onTokenCreated,
}: {
- props?: APIKeyProps;
- onTokenCreated: (token: string) => void;
+ token?: APIKeyProps;
+ onTokenCreated?: (token: string) => void;
} = { onTokenCreated: () => {} },
) {
const [showAddEditTokenModal, setShowAddEditTokenModal] = useState(false);
@@ -272,7 +275,7 @@ export function useAddEditTokenModal(
<AddEditTokenModal
showAddEditTokenModal={showAddEditTokenModal}
setShowAddEditTokenModal={setShowAddEditTokenModal}
- props={props}
+ token={token}
onTokenCreated={onTokenCreated}
/>
);