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.

clientAccessCheck

Steven Teyd1c325dfda58
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/people/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/people/page-client.tsx
index 80d3b157cf..1733a013a6 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/people/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/people/page-client.tsx
@@ -1,5 +1,6 @@
"use client";
+import { clientAccessCheck } from "@/lib/api/tokens/permissions";
import useUsers from "@/lib/swr/use-users";
import useWorkspace from "@/lib/swr/use-workspace";
import { WorkspaceUserProps } from "@/lib/types";
@@ -31,7 +32,7 @@ export default function WorkspacePeopleClient() {
"Members",
);
- const { isOwner } = useWorkspace();
+ const { role } = useWorkspace();
const { users } = useUsers({ invites: currentTab === "Invitations" });
@@ -52,9 +53,13 @@ export default function WorkspacePeopleClient() {
text="Invite"
onClick={() => setShowInviteTeammateModal(true)}
className="h-9"
- {...(!isOwner && {
- disabledTooltip:
- "Only workspace owners can invite new teammates.",
+ {...(clientAccessCheck({ action: "workspaces.write", role })
+ .error && {
+ disabledTooltip: clientAccessCheck({
+ action: "workspaces.write",
+ role,
+ customPermissionDescription: "invite new teammates",
+ }).error,
})}
/>
<Button
@@ -62,9 +67,13 @@ export default function WorkspacePeopleClient() {
variant="secondary"
onClick={() => setShowInviteCodeModal(true)}
className="h-9 space-x-0"
- {...(!isOwner && {
- disabledTooltip:
- "Only workspace owners can generate invite links for new teammates.",
+ {...(clientAccessCheck({ action: "workspaces.write", role })
+ .error && {
+ disabledTooltip: clientAccessCheck({
+ action: "workspaces.write",
+ role,
+ customPermissionDescription: "generate invite links",
+ }).error,
})}
/>
</div>
@@ -122,7 +131,13 @@ const UserCard = ({
}) => {
const [openPopover, setOpenPopover] = useState(false);
- const { isOwner } = useWorkspace();
+ const { role: userRole } = useWorkspace();
+
+ const permissionsError = clientAccessCheck({
+ action: "workspaces.write",
+ role: userRole,
+ customPermissionDescription: "edit roles or remove teammates",
+ }).error;
const { id, name, email, createdAt, role: currentRole, isMachine } = user;
@@ -182,11 +197,11 @@ const UserCard = ({
className={cn(
"rounded-md border border-gray-200 text-xs text-gray-500 focus:border-gray-600 focus:ring-gray-600",
{
- "cursor-not-allowed bg-gray-100": !isOwner,
+ "cursor-not-allowed bg-gray-100": permissionsError,
},
)}
value={role}
- disabled={!isOwner}
+ disabled={permissionsError ? true : false}
onChange={(e) => {
setRole(e.target.value as "owner" | "member");
setOpenPopover(false);
@@ -254,10 +269,9 @@ const UserCard = ({
icon={<ThreeDots className="h-5 w-5 text-gray-500" />}
className="h-8 space-x-0 px-1 py-2"
variant="outline"
- {...(!isOwner &&
+ {...(permissionsError &&
session?.user?.email !== email && {
- disabledTooltip:
- "Only workspace owners can edit roles or remove teammates.",
+ disabledTooltip: permissionsError,
})}
/>
</div>
diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.ts
index 9d4454dcc8..f3ee608bc8 100644
--- a/apps/web/lib/api/links/process-link.ts
+++ b/apps/web/lib/api/links/process-link.ts
@@ -11,6 +11,7 @@ import { NewLinkProps, ProcessedLinkProps, WorkspaceProps } from "@/lib/types";
import {
DUB_DOMAINS,
SHORT_DOMAIN,
+ combineWords,
getApexDomain,
getDomainWithoutWWW,
getUrlFromString,
@@ -111,20 +112,18 @@ export async function processLink<T extends Record<string, any>>({
geo ||
doIndex
) {
- const proFeaturesString = [
- proxy && "custom social media cards",
- password && "password protection",
- rewrite && "link cloaking",
- expiresAt && "link expiration",
- ios && "iOS targeting",
- android && "Android targeting",
- geo && "geo targeting",
- doIndex && "search engine indexing",
- ]
- .filter(Boolean)
- .join(", ")
- // final one should be "and" instead of comma
- .replace(/, ([^,]*)$/, " and $1");
+ const proFeaturesString = combineWords(
+ [
+ proxy && "custom social media cards",
+ password && "password protection",
+ rewrite && "link cloaking",
+ expiresAt && "link expiration",
+ ios && "iOS targeting",
+ android && "Android targeting",
+ geo && "geo targeting",
+ doIndex && "search engine indexing",
+ ].filter(Boolean) as string[],
+ );
return {
link: payload,
diff --git a/apps/web/lib/api/tokens/permissions.ts b/apps/web/lib/api/tokens/permissions.ts
index 6a6db7f01c..1183be95f1 100644
--- a/apps/web/lib/api/tokens/permissions.ts
+++ b/apps/web/lib/api/tokens/permissions.ts
@@ -1,5 +1,7 @@
+import { combineWords } from "@dub/utils";
+import { Role } from "@prisma/client";
import { DubApiError } from "../errors";
-import { PermissionAction } from "./scopes";
+import { PERMISSIONS, PermissionAction } from "./scopes";
// Check if the required scope is in the list of user scopes
export const throwIfNoAccess = ({
@@ -28,3 +30,26 @@ export const throwIfNoAccess = ({
message: `The provided key does not have the required permissions for this endpoint on the workspace 'ws_${workspaceId}'. Having the '${missingPermissions.join(" ")}' permission would allow this request to continue.`,
});
};
+
+export const clientAccessCheck = ({
+ action,
+ role,
+ customPermissionDescription,
+}: {
+ action: PermissionAction;
+ role: Role;
+ customPermissionDescription?: string;
+}) => {
+ const permission = PERMISSIONS.find((p) => p.action === action)!;
+ const allowedRoles = permission.roles;
+
+ if (allowedRoles.includes(role)) {
+ return {
+ error: false,
+ };
+ }
+
+ return {
+ error: `Only ${combineWords(allowedRoles)} can ${customPermissionDescription || permission.description}.`,
+ };
+};
diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index 3196eace41..088559928a 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -159,50 +159,62 @@ export const SCOPES: MasterScope[] = [
export const PERMISSIONS: Permission[] = [
{
action: "links.read",
+ description: "access links",
roles: ["owner", "member"],
},
{
action: "links.write",
+ description: "create, update, or delete links",
roles: ["owner", "member"],
},
{
action: "analytics.read",
+ description: "access analytics",
roles: ["owner", "member"],
},
{
action: "workspaces.read",
+ description: "access workspaces",
roles: ["owner", "member"],
},
{
action: "workspaces.write",
+ description: "create, update, or delete the current workspace",
roles: ["owner"],
},
{
action: "domains.read",
+ description: "access domains",
roles: ["owner", "member"],
},
{
action: "domains.write",
+ description: "create, update, or delete domains",
roles: ["owner"],
},
{
action: "tags.read",
+ description: "access tags",
roles: ["owner", "member"],
},
{
action: "tags.write",
+ description: "create, update, or delete tags",
roles: ["owner", "member"],
},
{
action: "tokens.read",
+ description: "access API keys",
roles: ["owner", "member"],
},
{
action: "tokens.write",
+ description: "create, update, or delete API keys",
roles: ["owner", "member"],
},
{
action: "conversions.write",
+ description: "track conversions",
roles: ["owner"],
},
];
@@ -364,6 +376,7 @@ type Resource = {
type Permission = {
action: PermissionAction;
+ description: string;
roles: Role[];
};
diff --git a/apps/web/lib/swr/use-workspace.ts b/apps/web/lib/swr/use-workspace.ts
index cb8dcb4216..77eb1b84f5 100644
--- a/apps/web/lib/swr/use-workspace.ts
+++ b/apps/web/lib/swr/use-workspace.ts
@@ -21,6 +21,7 @@ export default function useWorkspace() {
return {
...workspace,
nextPlan: workspace?.plan ? getNextPlan(workspace.plan) : PRO_PLAN,
+ role: (workspace?.users && workspace.users[0].role) || "member",
isOwner: workspace?.users && workspace.users[0].role === "owner",
exceededClicks: workspace && workspace.usage >= workspace.usageLimit,
exceededLinks: workspace && workspace.linksUsage >= workspace.linksLimit,
diff --git a/apps/web/ui/domains/domain-card.tsx b/apps/web/ui/domains/domain-card.tsx
index b57cb4a6ce..bca65f5be7 100644
--- a/apps/web/ui/domains/domain-card.tsx
+++ b/apps/web/ui/domains/domain-card.tsx
@@ -1,3 +1,4 @@
+import { clientAccessCheck } from "@/lib/api/tokens/permissions";
import useDomains from "@/lib/swr/use-domains";
import useWorkspace from "@/lib/swr/use-workspace";
import {
@@ -246,6 +247,12 @@ function Menu({
const { isMobile } = useMediaQuery();
+ const { role } = useWorkspace();
+ const permissionsError = clientAccessCheck({
+ action: "domains.write",
+ role,
+ }).error;
+
const { activeWorkspaceDomains } = useDomains();
const [openPopover, setOpenPopover] = useState(false);
@@ -455,6 +462,9 @@ function Menu({
onClick={() => {
setOpenPopover(!openPopover);
}}
+ {...(permissionsError && {
+ disabledTooltip: permissionsError,
+ })}
/>
</Popover>
</motion.div>
diff --git a/packages/ui/src/button.tsx b/packages/ui/src/button.tsx
index c2fed5470e..e0d97b7f03 100644
--- a/packages/ui/src/button.tsx
+++ b/packages/ui/src/button.tsx
@@ -56,7 +56,7 @@ const Button = forwardRef<HTMLButtonElement, ButtonProps>(
<Tooltip content={disabledTooltip}>
<div
className={cn(
- "flex h-10 w-full cursor-not-allowed items-center justify-center space-x-2 rounded-md border border-gray-200 bg-gray-100 px-4 text-sm text-gray-400 transition-all focus:outline-none",
+ "flex h-10 w-full cursor-not-allowed items-center justify-center gap-x-2 rounded-md border border-gray-200 bg-gray-100 px-4 text-sm text-gray-400 transition-all focus:outline-none",
{
"border-transparent bg-transparent":
variant?.endsWith("outline"),
@@ -65,7 +65,9 @@ const Button = forwardRef<HTMLButtonElement, ButtonProps>(
)}
>
{icon}
- <p className={cn(shortcut && "flex-1 text-left")}>{text}</p>
+ {text && (
+ <p className={cn(shortcut && "flex-1 text-left")}>{text}</p>
+ )}
{shortcut && (
<kbd
className={cn(
diff --git a/packages/utils/src/functions/combine-words.ts b/packages/utils/src/functions/combine-words.ts
new file mode 100644
index 0000000000..b316708d8e
--- /dev/null
+++ b/packages/utils/src/functions/combine-words.ts
@@ -0,0 +1,8 @@
+export const combineWords = (words: string[]) => {
+ return (
+ words
+ .join(", ")
+ // final one should be "and" instead of comma
+ .replace(/, ([^,]*)$/, " and $1")
+ );
+};
diff --git a/packages/utils/src/functions/index.ts b/packages/utils/src/functions/index.ts
index e219e67b13..2bff495c15 100644
--- a/packages/utils/src/functions/index.ts
+++ b/packages/utils/src/functions/index.ts
@@ -1,6 +1,7 @@
export * from "./capitalize";
export * from "./chunk";
export * from "./cn";
+export * from "./combine-words";
export * from "./construct-metadata";
export * from "./datetime";
export * from "./deep-equal";