Allow for admin to edit other user's event types

pull/9078/head
Joe Au-Yeung 2022-10-05 15:59:34 -04:00
parent 7e9226fabc
commit ce8af8b6a5
2 changed files with 12 additions and 4 deletions

View File

@ -12,19 +12,24 @@ export async function eventTypeById(
{ method, query, body, userId, isAdmin, prisma }: NextApiRequest, { method, query, body, userId, isAdmin, prisma }: NextApiRequest,
res: NextApiResponse<EventTypeResponse> res: NextApiResponse<EventTypeResponse>
) { ) {
if (body.userId && !isAdmin) {
res.status(401).json({ message: "Unauthorized" });
return;
}
const safeQuery = schemaQueryIdParseInt.safeParse(query); const safeQuery = schemaQueryIdParseInt.safeParse(query);
if (!safeQuery.success) { if (!safeQuery.success) {
res.status(400).json({ message: "Your query was invalid" }); res.status(400).json({ message: "Your query was invalid" });
return; return;
} }
const data = await prisma.user.findUnique({ const data = await prisma.user.findUnique({
where: { id: userId }, where: { id: body.userId || userId },
rejectOnNotFound: true, rejectOnNotFound: true,
select: { eventTypes: true }, select: { eventTypes: true },
}); });
const userEventTypes = data.eventTypes.map((eventType) => eventType.id); const userEventTypes = data.eventTypes.map((eventType) => eventType.id);
if (!isAdmin) { if (!userEventTypes.includes(safeQuery.data.id)) {
if (!userEventTypes.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); res.status(401).json({ message: "Unauthorized" });
return;
} else { } else {
switch (method) { switch (method) {
/** /**
@ -96,6 +101,7 @@ export async function eventTypeById(
*/ */
case "PATCH": case "PATCH":
const safeBody = schemaEventTypeEditBodyParams.safeParse(body); const safeBody = schemaEventTypeEditBodyParams.safeParse(body);
if (!safeBody.success) { if (!safeBody.success) {
{ {
res.status(400).json({ message: "Invalid request body" }); res.status(400).json({ message: "Invalid request body" });

View File

@ -44,7 +44,9 @@ async function createOrlistAllEventTypes(
error, error,
}); });
} else { } else {
const data = await prisma.eventType.findMany({}); const data = await prisma.eventType.findMany({
where: { userId: isAdmin && body.userId ? body.userId : userId },
});
const event_types = data.map((eventType) => schemaEventTypeReadPublic.parse(eventType)); const event_types = data.map((eventType) => schemaEventTypeReadPublic.parse(eventType));
if (event_types) res.status(200).json({ event_types }); if (event_types) res.status(200).json({ event_types });
} }