move action permission check to middleware

This commit is contained in:
Milo Schwartz
2024-11-05 23:55:46 -05:00
parent 03051878ef
commit 372e51c0a5
48 changed files with 266 additions and 936 deletions

View File

@@ -1,27 +1,32 @@
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { db } from '@server/db';
import { orgs } from '@server/db/schema';
import { eq } from 'drizzle-orm';
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { orgs } from "@server/db/schema";
import { eq } from "drizzle-orm";
import response from "@server/utils/response";
import HttpCode from '@server/types/HttpCode';
import createHttpError from 'http-errors';
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
import { fromError } from 'zod-validation-error';
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
const updateOrgParamsSchema = z.object({
orgId: z.string()
orgId: z.string(),
});
const updateOrgBodySchema = z.object({
name: z.string().min(1).max(255).optional(),
domain: z.string().min(1).max(255).optional(),
}).refine(data => Object.keys(data).length > 0, {
message: "At least one field must be provided for update"
});
const updateOrgBodySchema = z
.object({
name: z.string().min(1).max(255).optional(),
domain: z.string().min(1).max(255).optional(),
})
.refine((data) => Object.keys(data).length > 0, {
message: "At least one field must be provided for update",
});
export async function updateOrg(req: Request, res: Response, next: NextFunction): Promise<any> {
export async function updateOrg(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = updateOrgParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
@@ -46,14 +51,8 @@ export async function updateOrg(req: Request, res: Response, next: NextFunction)
const { orgId } = parsedParams.data;
const updateData = parsedBody.data;
// Check if the user has permission to list sites
const hasPermission = await checkUserActionPermission(ActionsEnum.updateOrg, req);
if (!hasPermission) {
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to perform this action'));
}
const updatedOrg = await db.update(orgs)
const updatedOrg = await db
.update(orgs)
.set(updateData)
.where(eq(orgs.orgId, orgId))
.returning();
@@ -76,6 +75,8 @@ export async function updateOrg(req: Request, res: Response, next: NextFunction)
});
} catch (error) {
logger.error(error);
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}