2021-08-19 12:27:01 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2022-07-22 17:27:06 +00:00
|
|
|
import { getTeamWithMembers } from "@calcom/lib/server/queries/teams";
|
2022-08-26 21:10:12 +00:00
|
|
|
import { closeComDeleteTeam } from "@calcom/lib/sync/SyncServiceManager";
|
2022-07-28 19:58:26 +00:00
|
|
|
import prisma from "@calcom/prisma";
|
2022-07-22 17:27:06 +00:00
|
|
|
|
2021-09-03 20:51:21 +00:00
|
|
|
import { getSession } from "@lib/auth";
|
2021-06-05 22:53:33 +00:00
|
|
|
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2021-08-19 12:27:01 +00:00
|
|
|
const session = await getSession({ req: req });
|
2021-06-05 22:53:33 +00:00
|
|
|
if (!session) {
|
2021-08-19 12:27:01 +00:00
|
|
|
return res.status(401).json({ message: "Not authenticated" });
|
2021-06-05 22:53:33 +00:00
|
|
|
}
|
2021-12-09 23:51:30 +00:00
|
|
|
if (!session.user?.id) {
|
|
|
|
console.log("Received session token without a user id.");
|
|
|
|
return res.status(500).json({ message: "Something went wrong." });
|
|
|
|
}
|
|
|
|
if (!req.query.team) {
|
|
|
|
console.log("Missing team query param.");
|
|
|
|
return res.status(500).json({ message: "Something went wrong." });
|
|
|
|
}
|
|
|
|
|
|
|
|
const teamId = parseInt(req.query.team as string);
|
2021-06-05 22:53:33 +00:00
|
|
|
|
2021-12-09 23:51:30 +00:00
|
|
|
// GET /api/teams/{team}
|
|
|
|
if (req.method === "GET") {
|
|
|
|
const team = await getTeamWithMembers(teamId);
|
|
|
|
return res.status(200).json({ team });
|
|
|
|
}
|
2021-06-05 22:53:33 +00:00
|
|
|
// DELETE /api/teams/{team}
|
|
|
|
if (req.method === "DELETE") {
|
2021-09-22 10:43:32 +00:00
|
|
|
const membership = await prisma.membership.findFirst({
|
|
|
|
where: {
|
|
|
|
userId: session.user.id,
|
2021-12-09 23:51:30 +00:00
|
|
|
teamId,
|
2021-09-22 10:43:32 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!membership || membership.role !== "OWNER") {
|
|
|
|
console.log(`User ${session.user.id} tried deleting an organization they don't own.`);
|
|
|
|
return res.status(403).json({ message: "Forbidden." });
|
|
|
|
}
|
|
|
|
|
2021-08-19 12:27:01 +00:00
|
|
|
await prisma.membership.delete({
|
2021-06-05 22:53:33 +00:00
|
|
|
where: {
|
2021-12-09 23:51:30 +00:00
|
|
|
userId_teamId: { userId: session.user.id, teamId },
|
2021-08-19 12:27:01 +00:00
|
|
|
},
|
2021-06-05 22:53:33 +00:00
|
|
|
});
|
2022-08-26 21:10:12 +00:00
|
|
|
const deletedTeam = await prisma.team.delete({
|
2021-06-05 22:53:33 +00:00
|
|
|
where: {
|
2021-12-09 23:51:30 +00:00
|
|
|
id: teamId,
|
2021-06-05 22:53:33 +00:00
|
|
|
},
|
|
|
|
});
|
2022-08-26 21:10:12 +00:00
|
|
|
|
|
|
|
// Sync Services: Close.com
|
|
|
|
closeComDeleteTeam(deletedTeam);
|
|
|
|
|
2021-06-05 22:53:33 +00:00
|
|
|
return res.status(204).send(null);
|
|
|
|
}
|
2021-08-19 12:27:01 +00:00
|
|
|
}
|