The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
chore: Refactor workspace for improved token handling and permission check
Kiran Kf49dfdb2a2fe
diff --git a/apps/web/lib/auth/workspace-edge.ts b/apps/web/lib/auth/workspace-edge.tsindex 2c7925eee7..9fc8b464fa 100644--- a/apps/web/lib/auth/workspace-edge.ts+++ b/apps/web/lib/auth/workspace-edge.ts@@ -3,7 +3,7 @@ import {exceededLimitError,handleAndReturnErrorResponse,} from "@/lib/api/errors";-import { PlanProps, TokenFound, WorkspaceProps } from "@/lib/types";+import { PlanProps, WorkspaceProps } from "@/lib/types";import { ratelimit } from "@/lib/upstash";import { API_DOMAIN, getSearchParams } from "@dub/utils";import { waitUntil } from "@vercel/functions";@@ -89,6 +89,7 @@ export const withWorkspaceEdge = (let workspaceId: string | undefined;let workspaceSlug: string | undefined;let scopes: Scope[] = [];+ let token: any | null = null;const idOrSlug =params?.idOrSlug ||@@ -105,25 +106,19 @@ export const withWorkspaceEdge = (});}- if (idOrSlug.startsWith("ws_")) {- workspaceId = idOrSlug.replace("ws_", "");- } else {- workspaceSlug = idOrSlug;- }-if (apiKey) {const isRestrictedToken = apiKey.startsWith("dub_");- const tokenTable = isRestrictedToken ? "restrictedToken" : "token";const hashedKey = await hashToken(apiKey);-- const token: TokenFound = await (- prismaEdge[tokenTable] as any- ).findUnique({+ const prismaArgs = {where: {hashedKey,},select: {- ...(isRestrictedToken && { scopes: true, ratelimit: true }),+ ...(isRestrictedToken && {+ scopes: true,+ rateLimit: true,+ projectId: true,+ }),user: {select: {id: true,@@ -133,7 +128,13 @@ export const withWorkspaceEdge = (},},},- });+ };++ if (isRestrictedToken) {+ token = await prismaEdge.restrictedToken.findUnique(prismaArgs);+ } else {+ token = await prismaEdge.token.findUnique(prismaArgs);+ }if (!token || !token.user) {throw new DubApiError({@@ -143,7 +144,7 @@ export const withWorkspaceEdge = (}// Rate limit checks for API keys- const rateLimit = "rateLimit" in token ? token.rateLimit : 600;+ const rateLimit = token?.rateLimit || 600;const { success, limit, reset, remaining } = await ratelimit(rateLimit,@@ -164,19 +165,24 @@ export const withWorkspaceEdge = (}waitUntil(- // update last used time- (prismaEdge[tokenTable] as any).update({- where: {- hashedKey,- },- data: {- lastUsed: new Date(),- },- }),- );+ // update last used time for the token+ (async () => {+ const prismaArgs = {+ where: {+ hashedKey,+ },+ data: {+ lastUsed: new Date(),+ },+ };- // @ts-ignore- scopes = isRestrictedToken ? token.scopes.split(" ") : availableScopes;+ if (isRestrictedToken) {+ await prismaEdge.restrictedToken.update(prismaArgs);+ } else {+ await prismaEdge.token.update(prismaArgs);+ }+ })(),+ );session = {user: {@@ -200,6 +206,12 @@ export const withWorkspaceEdge = (}}+ if (idOrSlug.startsWith("ws_")) {+ workspaceId = idOrSlug.replace("ws_", "");+ } else {+ workspaceSlug = idOrSlug;+ }+const workspace = (await prismaEdge.project.findUnique({where: {id: workspaceId || undefined,@@ -231,8 +243,10 @@ export const withWorkspaceEdge = (});}- // For session requests, find the scopes based on the user's role- if (session && !apiKey) {+ // Find scopes based on the token or user's role+ if (token && "scopes" in token) {+ scopes = (token.scopes?.split(" ") as Scope[]) || [];+ } else {scopes = roleScopesMapping[workspace.users[0].role];}diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex 358b163e6c..532f456f20 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -4,7 +4,7 @@ import {handleAndReturnErrorResponse,} from "@/lib/api/errors";import { prisma } from "@/lib/prisma";-import { PlanProps, TokenFound, WorkspaceProps } from "@/lib/types";+import { PlanProps, WorkspaceProps } from "@/lib/types";import { ratelimit } from "@/lib/upstash";import {API_DOMAIN,@@ -15,11 +15,7 @@ import {import { Link as LinkProps } from "@prisma/client";import { waitUntil } from "@vercel/functions";import { throwIfNoAccess } from "../api/tokens/permissions";-import {- Scope,- availableScopes,- roleScopesMapping,-} from "../api/tokens/scopes";+import { Scope, roleScopesMapping } from "../api/tokens/scopes";import { isBetaTester } from "../edge-config";import { hashToken } from "./hash-token";import { Session, getSession } from "./utils";@@ -114,6 +110,7 @@ export const withWorkspace = (let workspaceId: string | undefined;let workspaceSlug: string | undefined;let scopes: Scope[] = [];+ let token: any | null = null;const idOrSlug =params?.idOrSlug ||@@ -141,23 +138,19 @@ export const withWorkspace = (}}- if (idOrSlug.startsWith("ws_")) {- workspaceId = idOrSlug.replace("ws_", "");- } else {- workspaceSlug = idOrSlug;- }-if (apiKey) {const isRestrictedToken = apiKey.startsWith("dub_");- const tokenTable = isRestrictedToken ? "restrictedToken" : "token";const hashedKey = await hashToken(apiKey);-- const token: TokenFound = await (prisma[tokenTable] as any).findUnique({+ const prismaArgs = {where: {hashedKey,},select: {- ...(isRestrictedToken && { scopes: true, rateLimit: true }),+ ...(isRestrictedToken && {+ scopes: true,+ rateLimit: true,+ projectId: true,+ }),user: {select: {id: true,@@ -167,7 +160,13 @@ export const withWorkspace = (},},},- });+ };++ if (isRestrictedToken) {+ token = await prisma.restrictedToken.findUnique(prismaArgs);+ } else {+ token = await prisma.token.findUnique(prismaArgs);+ }if (!token || !token.user) {throw new DubApiError({@@ -177,7 +176,7 @@ export const withWorkspace = (}// Rate limit checks for API keys- const rateLimit = "rateLimit" in token ? token.rateLimit : 600;+ const rateLimit = token?.rateLimit || 600;const { success, limit, reset, remaining } = await ratelimit(rateLimit,@@ -198,20 +197,25 @@ export const withWorkspace = (}waitUntil(- // update last used time- (prisma[tokenTable] as any).update({- where: {- hashedKey,- },- data: {- lastUsed: new Date(),- },- }),+ // update last used time for the token+ (async () => {+ const prismaArgs = {+ where: {+ hashedKey,+ },+ data: {+ lastUsed: new Date(),+ },+ };++ if (isRestrictedToken) {+ await prisma.restrictedToken.update(prismaArgs);+ } else {+ await prisma.token.update(prismaArgs);+ }+ })(),);- // @ts-ignore- scopes = isRestrictedToken ? token.scopes.split(" ") : availableScopes;-session = {user: {id: token.user.id,@@ -222,6 +226,7 @@ export const withWorkspace = (};} else {session = await getSession();+if (!session?.user?.id) {throw new DubApiError({code: "unauthorized",@@ -230,6 +235,12 @@ export const withWorkspace = (}}+ if (idOrSlug.startsWith("ws_")) {+ workspaceId = idOrSlug.replace("ws_", "");+ } else {+ workspaceSlug = idOrSlug;+ }+let [workspace, link] = (await Promise.all([prisma.project.findUnique({where: {@@ -284,16 +295,18 @@ export const withWorkspace = (})),])) as [WorkspaceProps, LinkProps | undefined];+ // workspace doesn't existif (!workspace || !workspace.users) {- // workspace doesn't existthrow new DubApiError({code: "not_found",message: "Workspace not found.",});}- // For session requests, find the scopes based on the user's role- if (session && !apiKey) {+ // Find scopes based on the token or user's role+ if (token && "scopes" in token) {+ scopes = (token.scopes?.split(" ") as Scope[]) || [];+ } else {scopes = roleScopesMapping[workspace.users[0].role];}