fosrl.pangolin/server/routers/role/createRole.ts

114 lines
3.1 KiB
TypeScript
Raw Normal View History

import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { orgs, Role, roleActions, roles } from "@server/db/schema";
2024-10-12 21:36:14 -04:00
import response from "@server/utils/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { ActionsEnum } from "@server/auth/actions";
import { eq, and } from "drizzle-orm";
2024-10-12 21:36:14 -04:00
const createRoleParamsSchema = z.object({
orgId: z.string(),
2024-10-12 21:36:14 -04:00
});
const createRoleSchema = z.object({
name: z.string().min(1).max(255),
description: z.string().optional(),
});
2024-11-09 23:59:19 -05:00
export const defaultRoleAllowedActions: ActionsEnum[] = [
ActionsEnum.getOrg,
ActionsEnum.getResource,
ActionsEnum.listResources,
];
export type CreateRoleBody = z.infer<typeof createRoleSchema>;
export type CreateRoleResponse = Role;
export async function createRole(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
2024-10-12 21:36:14 -04:00
try {
const parsedBody = createRoleSchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
2024-10-12 21:36:14 -04:00
)
);
}
const roleData = parsedBody.data;
const parsedParams = createRoleParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
2024-10-12 21:36:14 -04:00
)
);
}
const { orgId } = parsedParams.data;
const allRoles = await db
.select({
roleId: roles.roleId,
name: roles.name,
})
.from(roles)
.leftJoin(orgs, eq(roles.orgId, orgs.orgId))
.where(and(eq(roles.name, roleData.name), eq(roles.orgId, orgId)));
// make sure name is unique
if (allRoles.length > 0) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Role with that name already exists"
)
);
}
const newRole = await db
.insert(roles)
.values({
...roleData,
orgId,
})
.returning();
2024-10-12 21:36:14 -04:00
await db
.insert(roleActions)
.values(
2024-11-09 23:59:19 -05:00
defaultRoleAllowedActions.map((action) => ({
roleId: newRole[0].roleId,
actionId: action,
orgId,
}))
)
.execute();
return response<Role>(res, {
2024-10-12 21:36:14 -04:00
data: newRole[0],
success: true,
error: false,
message: "Role created successfully",
status: HttpCode.CREATED,
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
2024-10-12 21:36:14 -04:00
}
}