mirror of
https://github.com/fosrl/pangolin.git
synced 2025-05-13 13:50:40 +01:00
70 lines
1.8 KiB
TypeScript
70 lines
1.8 KiB
TypeScript
import { Request, Response, NextFunction } from "express";
|
|
import { db } from "@server/db";
|
|
import { userOrgs } from "@server/db/schema";
|
|
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"
|
|
)
|
|
);
|
|
}
|
|
}
|