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.

5.6 KB
Raw Blame
import { DubApiError } from "@/lib/api/errors";
import { throwIfNoAccess } from "@/lib/api/tokens/throw-if-no-access";
import { assertRoleAllowedForPlan } from "@/lib/api/workspaces/assert-role-plan";
import { withWorkspace } from "@/lib/auth";
import { generateRandomName } from "@/lib/names";
import { prisma } from "@/lib/prisma";
import {
  getWorkspaceUsersQuerySchema,
  workspaceUserSchema,
} from "@/lib/zod/schemas/workspaces";
import { pluralize } from "@dub/utils";
import { WorkspaceRole } from "@prisma/client";
import { NextResponse } from "next/server";
import * as z from "zod/v4";

// GET /api/workspaces/[idOrSlug]/users – get users for a specific workspace
export const GET = withWorkspace(
  async ({ workspace, searchParams }) => {
    const { search, role } = getWorkspaceUsersQuerySchema.parse(searchParams);

    const users = await prisma.projectUsers.findMany({
      where: {
        projectId: workspace.id,
        role,
        ...(search && {
          user: {
            OR: [
              { name: { contains: search } },
              { email: { contains: search } },
            ],
          },
        }),
      },
      include: {
        user: true,
      },
      orderBy: {
        createdAt: "asc",
      },
    });

    const parsedUsers = users.map(({ user, ...rest }) =>
      workspaceUserSchema.parse({
        ...rest,
        ...user,
        name: user.name || user.email || generateRandomName(),
        createdAt: rest.createdAt, // preserve the createdAt field from ProjectUsers
      }),
    );

    return NextResponse.json(parsedUsers);
  },
  {
    requiredPermissions: ["workspaces.read"],
    requiredRoles: ["owner", "member", "billing"],
  },
);

const updateRoleSchema = z.object({
  userId: z.string().min(1),
  role: z.enum(WorkspaceRole),
});

// PATCH /api/workspaces/[idOrSlug]/users – update a user's role for a specific workspace
export const PATCH = withWorkspace(
  async ({ req, workspace }) => {
    const { userId, role } = updateRoleSchema.parse(await req.json());

    assertRoleAllowedForPlan({
      role,
      plan: workspace.plan,
    });

    const workspaceUser = await prisma.projectUsers.update({
      where: {
        userId_projectId: {
          projectId: workspace.id,
          userId,
        },
        user: {
          isMachine: false,
        },
      },
      data: {
        role,
      },
    });

    return NextResponse.json(workspaceUser);
  },
  {
    requiredPermissions: ["workspaces.write"],
  },
);

const removeUserSchema = z.object({
  userId: z.string().min(1),
});

// DELETE /api/workspaces/[idOrSlug]/users – remove a user from a workspace or leave a workspace
export const DELETE = withWorkspace(
  async ({ searchParams, workspace, session, permissions }) => {
    const { userId } = removeUserSchema.parse(searchParams);

    if (userId !== session.user.id) {
      throwIfNoAccess({
        permissions,
        requiredPermissions: ["workspaces.write"],
        workspaceId: workspace.id,
      });
    }

    const [projectUser, totalOwners] = await Promise.all([
      prisma.projectUsers.findUnique({
        where: {
          userId_projectId: {
            projectId: workspace.id,
            userId,
          },
        },
        select: {
          role: true,
          user: {
            select: {
              id: true,
              isMachine: true,
              defaultWorkspace: true,
            },
          },
        },
      }),

      prisma.projectUsers.count({
        where: {
          projectId: workspace.id,
          role: "owner",
        },
      }),
    ]);

    if (!projectUser) {
      throw new DubApiError({
        code: "not_found",
        message: "User not found.",
      });
    }

    // If there is only one owner and the user is an owner and the user is trying to remove themselves
    if (
      totalOwners === 1 &&
      projectUser.role === "owner" &&
      userId === session.user.id
    ) {
      throw new DubApiError({
        code: "bad_request",
        message:
          "Cannot remove owner from workspace. Please transfer ownership to another user first.",
      });
    }

    const activeRestrictedTokens = await prisma.restrictedToken.count({
      where: {
        projectId: workspace.id,
        userId,
        lastUsed: {
          not: null,
        },
      },
    });

    if (activeRestrictedTokens) {
      const tokenTense = pluralize("token", activeRestrictedTokens);
      throw new DubApiError({
        code: "bad_request",
        message: `This user has ${activeRestrictedTokens} active restricted ${tokenTense}. Please remove the ${tokenTense} first before removing the user from the workspace.`,
      });
    }

    await Promise.all([
      // Remove the user from the workspace
      prisma.projectUsers.delete({
        where: {
          userId_projectId: {
            projectId: workspace.id,
            userId,
          },
        },
      }),

      // Remove tokens associated with the user from the workspace
      prisma.restrictedToken.deleteMany({
        where: {
          projectId: workspace.id,
          userId,
        },
      }),

      // Remove the default workspace for the user if they are leaving the workspace
      workspace.slug === projectUser.user.defaultWorkspace &&
        prisma.user.update({
          where: {
            id: userId,
          },
          data: {
            defaultWorkspace: null,
          },
        }),
    ]);

    // delete the user if it's a machine user
    if (projectUser.user.isMachine) {
      await prisma.user.delete({
        where: {
          id: userId,
        },
      });
    }

    return NextResponse.json({
      userId,
    });
  },
);