pangolin/server/middlewares/verifySetResourceUsers.ts
2025-03-23 17:11:48 -04:00

70 lines
1.8 KiB
TypeScript

import { Request, Response, NextFunction } from "express";
import { db } from "@server/db";
import { userOrgs } from "@server/db/schemas";
import { and, eq, inArray, or } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
export async function verifySetResourceUsers(
req: Request,
res: Response,
next: NextFunction
) {
const userId = req.user!.userId;
const userIds = req.body.userIds;
if (!userId) {
return next(
createHttpError(HttpCode.UNAUTHORIZED, "User not authenticated")
);
}
if (!req.userOrg) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have access to this user"
)
);
}
if (!userIds) {
return next(createHttpError(HttpCode.BAD_REQUEST, "Invalid user IDs"));
}
if (userIds.length === 0) {
return next();
}
try {
const orgId = req.userOrg.orgId;
// get all userOrgs for the users
const userOrgsData = await db
.select()
.from(userOrgs)
.where(
and(
inArray(userOrgs.userId, userIds),
eq(userOrgs.orgId, orgId)
)
);
if (userOrgsData.length !== userIds.length) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have access to this user"
)
);
}
return next();
} catch (error) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Error checking if user has access to this user"
)
);
}
}