fosrl.pangolin/server/routers/user/addUserAction.ts

92 lines
2.6 KiB
TypeScript
Raw Normal View History

import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { userActions, users } from "@server/db/schema";
2024-10-12 22:31:24 -04:00
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 { eq } from "drizzle-orm";
import { fromError } from "zod-validation-error";
2024-10-12 22:31:24 -04:00
const addUserActionSchema = z.object({
userId: z.string(),
actionId: z.string(),
2024-10-14 15:11:18 -04:00
orgId: z.string(),
2024-10-12 22:31:24 -04:00
});
export async function addUserAction(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
2024-10-12 22:31:24 -04:00
try {
const parsedBody = addUserActionSchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
2024-10-12 22:31:24 -04:00
)
);
}
const { userId, actionId, orgId } = parsedBody.data;
// Check if the user has permission to add user actions
const hasPermission = await checkUserActionPermission(
ActionsEnum.addUserAction,
req
);
2024-10-12 22:31:24 -04:00
if (!hasPermission) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have permission to perform this action"
)
);
2024-10-12 22:31:24 -04:00
}
// Check if the user exists
const user = await db
.select()
.from(users)
.where(eq(users.userId, userId))
.limit(1);
2024-10-12 22:31:24 -04:00
if (user.length === 0) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`User with ID ${userId} not found`
)
);
2024-10-12 22:31:24 -04:00
}
const newUserAction = await db
.insert(userActions)
.values({
userId,
actionId,
orgId,
})
.returning();
2024-10-12 22:31:24 -04:00
return response(res, {
data: newUserAction[0],
success: true,
error: false,
message: "Action added to user successfully",
status: HttpCode.CREATED,
});
} catch (error) {
logger.error(error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"An error occurred..."
)
);
2024-10-12 22:31:24 -04:00
}
2024-10-13 17:13:47 -04:00
}