2024-11-05 22:38:57 -05:00
|
|
|
import { Request, Response, NextFunction } from "express";
|
|
|
|
import { db } from "@server/db";
|
|
|
|
import { roles, userOrgs } from "@server/db/schema";
|
|
|
|
import { and, eq } from "drizzle-orm";
|
|
|
|
import createHttpError from "http-errors";
|
|
|
|
import HttpCode from "@server/types/HttpCode";
|
|
|
|
import logger from "@server/logger";
|
|
|
|
|
|
|
|
export async function verifyRoleAccess(
|
|
|
|
req: Request,
|
|
|
|
res: Response,
|
|
|
|
next: NextFunction
|
|
|
|
) {
|
|
|
|
const userId = req.user?.userId;
|
|
|
|
const roleId = parseInt(
|
|
|
|
req.params.roleId || req.body.roleId || req.query.roleId
|
|
|
|
);
|
2024-10-12 21:36:14 -04:00
|
|
|
|
|
|
|
if (!userId) {
|
2024-11-05 22:38:57 -05:00
|
|
|
return next(
|
|
|
|
createHttpError(HttpCode.UNAUTHORIZED, "User not authenticated")
|
|
|
|
);
|
2024-10-12 21:36:14 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if (isNaN(roleId)) {
|
2024-11-05 22:38:57 -05:00
|
|
|
return next(createHttpError(HttpCode.BAD_REQUEST, "Invalid role ID"));
|
2024-10-12 21:36:14 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2024-11-05 22:38:57 -05:00
|
|
|
const role = await db
|
|
|
|
.select()
|
2024-10-12 21:36:14 -04:00
|
|
|
.from(roles)
|
|
|
|
.where(eq(roles.roleId, roleId))
|
|
|
|
.limit(1);
|
|
|
|
|
|
|
|
if (role.length === 0) {
|
2024-11-05 22:38:57 -05:00
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.NOT_FOUND,
|
|
|
|
`Role with ID ${roleId} not found`
|
|
|
|
)
|
|
|
|
);
|
2024-10-12 21:36:14 -04:00
|
|
|
}
|
|
|
|
|
2024-11-09 23:59:19 -05:00
|
|
|
if (!req.userOrg) {
|
2024-11-05 22:38:57 -05:00
|
|
|
const userOrgRole = await db
|
|
|
|
.select()
|
|
|
|
.from(userOrgs)
|
|
|
|
.where(
|
|
|
|
and(
|
|
|
|
eq(userOrgs.userId, userId),
|
|
|
|
eq(userOrgs.orgId, role[0].orgId!)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
.limit(1);
|
2024-11-09 23:59:19 -05:00
|
|
|
req.userOrg = userOrgRole[0];
|
2024-11-05 22:38:57 -05:00
|
|
|
}
|
2024-10-12 21:36:14 -04:00
|
|
|
|
2024-11-09 23:59:19 -05:00
|
|
|
if (!req.userOrg) {
|
2024-11-05 22:38:57 -05:00
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.FORBIDDEN,
|
|
|
|
"User does not have access to this organization"
|
|
|
|
)
|
|
|
|
);
|
2024-10-12 21:36:14 -04:00
|
|
|
}
|
|
|
|
|
2024-11-09 23:59:19 -05:00
|
|
|
if (req.userOrg.orgId !== role[0].orgId) {
|
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.FORBIDDEN,
|
|
|
|
"Role does not belong to the organization"
|
|
|
|
)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
req.userOrgRoleId = req.userOrg.roleId;
|
|
|
|
req.userOrgId = req.userOrg.orgId;
|
2024-10-12 21:36:14 -04:00
|
|
|
|
|
|
|
return next();
|
|
|
|
} catch (error) {
|
2024-11-05 22:38:57 -05:00
|
|
|
logger.error("Error verifying role access:", error);
|
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.INTERNAL_SERVER_ERROR,
|
|
|
|
"Error verifying role access"
|
|
|
|
)
|
|
|
|
);
|
2024-10-12 21:36:14 -04:00
|
|
|
}
|
2024-10-13 17:13:47 -04:00
|
|
|
}
|