fosrl.pangolin/server/routers/user/removeUserOrg.ts

84 lines
2.3 KiB
TypeScript
Raw Normal View History

import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { userOrgs, userResources, users, userSites } from "@server/db/schema";
import { and, eq } from "drizzle-orm";
2025-01-01 21:41:31 -05:00
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
2024-10-01 21:53:49 -04:00
2024-12-21 21:01:12 -05:00
const removeUserSchema = z
.object({
userId: z.string(),
orgId: z.string()
})
.strict();
2024-10-01 21:34:07 -04:00
export async function removeUserOrg(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
2024-10-06 18:05:20 -04:00
try {
2024-10-12 22:31:24 -04:00
const parsedParams = removeUserSchema.safeParse(req.params);
2024-10-06 18:05:20 -04:00
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
2024-10-06 18:05:20 -04:00
)
);
}
2024-10-01 21:53:49 -04:00
2024-10-12 22:31:24 -04:00
const { userId, orgId } = parsedParams.data;
2024-10-01 21:53:49 -04:00
// get the user first
const user = await db
.select()
.from(userOrgs)
.where(eq(userOrgs.userId, userId));
if (!user || user.length === 0) {
return next(createHttpError(HttpCode.NOT_FOUND, "User not found"));
}
if (user[0].isOwner) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Cannot remove owner from org"
)
);
}
await db.transaction(async (trx) => {
await trx
.delete(userOrgs)
.where(
and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId))
);
await trx
.delete(userResources)
.where(eq(userResources.userId, userId));
await trx.delete(userSites).where(eq(userSites.userId, userId));
});
2024-10-01 21:53:49 -04:00
2024-10-06 18:05:20 -04:00
return response(res, {
data: null,
success: true,
error: false,
2024-11-03 17:28:12 -05:00
message: "User remove from org successfully",
2024-12-21 21:01:12 -05:00
status: HttpCode.OK
2024-10-06 18:05:20 -04:00
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
2024-10-06 18:05:20 -04:00
}
}