add roles input on resource and make spacing more consistent

This commit is contained in:
Milo Schwartz
2024-11-15 18:25:27 -05:00
parent 8e64b5e0e9
commit 28bae40390
36 changed files with 1235 additions and 724 deletions

View File

@@ -1,10 +1,16 @@
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 { and, eq, inArray } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import logger from "@server/logger";
import { z } from "zod";
import { fromError } from "zod-validation-error";
const verifyRoleAccessSchema = z.object({
roleIds: z.array(z.number().int().positive()).optional(),
});
export async function verifyRoleAccess(
req: Request,
@@ -12,7 +18,7 @@ export async function verifyRoleAccess(
next: NextFunction
) {
const userId = req.user?.userId;
const roleId = parseInt(
const singleRoleId = parseInt(
req.params.roleId || req.body.roleId || req.query.roleId
);
@@ -22,61 +28,61 @@ export async function verifyRoleAccess(
);
}
if (isNaN(roleId)) {
return next(createHttpError(HttpCode.BAD_REQUEST, "Invalid role ID"));
const parsedBody = verifyRoleAccessSchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { roleIds } = parsedBody.data;
const allRoleIds = roleIds || (isNaN(singleRoleId) ? [] : [singleRoleId]);
if (allRoleIds.length === 0) {
return next();
}
try {
const role = await db
const rolesData = await db
.select()
.from(roles)
.where(eq(roles.roleId, roleId))
.limit(1);
.where(inArray(roles.roleId, allRoleIds));
if (role.length === 0) {
if (rolesData.length !== allRoleIds.length) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Role with ID ${roleId} not found`
"One or more roles not found"
)
);
}
if (!req.userOrg) {
// Check user access to each role's organization
for (const role of rolesData) {
const userOrgRole = await db
.select()
.from(userOrgs)
.where(
and(
eq(userOrgs.userId, userId),
eq(userOrgs.orgId, role[0].orgId!)
eq(userOrgs.orgId, role.orgId!)
)
)
.limit(1);
req.userOrg = userOrgRole[0];
}
if (!req.userOrg) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have access to this organization"
)
);
if (userOrgRole.length === 0) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
`User does not have access to organization for role ID ${role.roleId}`
)
);
}
}
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;
return next();
} catch (error) {
logger.error("Error verifying role access:", error);