Scheduling infrastructure for absolutely everyone.
feat: initial isAdmin work for events and attendees
Agusti Fernandez Pardoed1bc8015acf
diff --git a/lib/helpers/verifyApiKey.ts b/lib/helpers/verifyApiKey.tsindex c45f3d3c3fa..c3977ca94f6 100644--- a/lib/helpers/verifyApiKey.ts+++ b/lib/helpers/verifyApiKey.ts@@ -4,12 +4,15 @@ import { NextMiddleware } from "next-api-middleware";import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys";import prisma from "@calcom/prisma";+import { isAdminGuard } from "@lib/utils/isAdmin";+/** @todo figure how to use the one from `@calcom/types`fi *//** @todo: remove once `@calcom/types` is updated with it.*/declare module "next" {export interface NextApiRequest extends IncomingMessage {userId: number;method: string;+ isAdmin: boolean;query: { [key: string]: string | string[] };}}@@ -39,5 +42,8 @@ export const verifyApiKey: NextMiddleware = async (req, res, next) => {if (!apiKey.userId) return res.status(404).json({ error: "No user found for this apiKey" });/* We save the user id in the request for later use */req.userId = apiKey.userId;+ /* We save the isAdmin boolean here for later use */+ req.isAdmin = await isAdminGuard(req.userId);+await next();};diff --git a/lib/validations/booking.ts b/lib/validations/booking.tsindex b61d6913fd9..a8a4b52c374 100644--- a/lib/validations/booking.ts+++ b/lib/validations/booking.ts@@ -24,7 +24,6 @@ export const schemaBookingCreateBodyParams = schemaBookingBaseBodyParams.merge(sconst schemaBookingEditParams = z.object({- uid: z.string().optional(),title: z.string().optional(),startTime: z.date().optional(),endTime: z.date().optional(),diff --git a/pages/api/attendees/[id].ts b/pages/api/attendees/[id].tsindex a1674d87a4a..a72dbf5812c 100644--- a/pages/api/attendees/[id].ts+++ b/pages/api/attendees/[id].ts@@ -11,7 +11,7 @@ import {} from "@lib/validations/shared/queryIdTransformParseInt";export async function attendeeById(- { method, query, body, userId }: NextApiRequest,+ { method, query, body, userId, isAdmin }: NextApiRequest,res: NextApiResponse<AttendeeResponse>) {const safeQuery = schemaQueryIdParseInt.safeParse(query);@@ -33,9 +33,11 @@ export async function attendeeById(.flat().map((attendee) => attendee.id));- // @note: Here we make sure to only return attendee's of the user's own bookings.- if (!userBookingsAttendeeIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" });- else {+ // @note: Here we make sure to only return attendee's of the user's own bookings if the user is not an admin.+ if (!isAdmin) {+ if (!userBookingsAttendeeIds.includes(safeQuery.data.id))+ res.status(401).json({ message: "Unauthorized" });+ } else {switch (method) {/*** @swaggerdiff --git a/pages/api/attendees/index.ts b/pages/api/attendees/index.tsindex eaae0b28ffa..6b2c4fc415a 100644--- a/pages/api/attendees/index.ts+++ b/pages/api/attendees/index.ts@@ -1,24 +1,30 @@import type { NextApiRequest, NextApiResponse } from "next";-import db from "@calcom/prisma";+import prisma from "@calcom/prisma";import { withMiddleware } from "@lib/helpers/withMiddleware";import { AttendeeResponse, AttendeesResponse } from "@lib/types";import { schemaAttendeeCreateBodyParams, schemaAttendeeReadPublic } from "@lib/validations/attendee";async function createOrlistAllAttendees(- { method, userId, body }: NextApiRequest,+ { method, userId, body, isAdmin }: NextApiRequest,res: NextApiResponse<AttendeesResponse | AttendeeResponse>) {- const userBookings = await db.booking.findMany({- where: {- userId,- },- include: {- attendees: true,- },- });- const attendees = userBookings.map((booking) => booking.attendees).flat();+ let attendees;+ if (!isAdmin) {+ const userBookings = await prisma.booking.findMany({+ where: {+ userId,+ },+ include: {+ attendees: true,+ },+ });+ attendees = userBookings.map((booking) => booking.attendees).flat();+ } else {+ const data = await prisma.attendee.findMany();+ attendees = data.map((attendee) => schemaAttendeeReadPublic.parse(attendee));+ }if (method === "GET") {/*** @swagger@@ -37,12 +43,7 @@ async function createOrlistAllAttendees(* description: No attendees were found*/if (attendees) res.status(200).json({ attendees });- else- (error: Error) =>- res.status(404).json({- message: "No Attendees were found",- error,- });+ else (error: Error) => res.status(400).json({ error });} else if (method === "POST") {/*** @swagger@@ -90,16 +91,40 @@ async function createOrlistAllAttendees(res.status(400).json({ message: "Invalid request body", error: safePost.error });return;}- const userWithBookings = await db.user.findUnique({ where: { id: userId }, include: { bookings: true } });- if (!userWithBookings) {- res.status(404).json({ message: "User not found" });- return;- }- const userBookingIds = userWithBookings.bookings.map((booking: { id: number }) => booking.id).flat();- // Here we make sure to only return attendee's of the user's own bookings.- if (!userBookingIds.includes(safePost.data.bookingId)) res.status(401).json({ message: "Unauthorized" });- else {- const data = await db.attendee.create({+ if (!isAdmin) {+ const userWithBookings = await prisma.user.findUnique({+ where: { id: userId },+ include: { bookings: true },+ });+ if (!userWithBookings) {+ res.status(404).json({ message: "User not found" });+ return;+ }+ const userBookingIds = userWithBookings.bookings.map((booking: { id: number }) => booking.id).flat();+ // Here we make sure to only return attendee's of the user's own bookings.+ if (!userBookingIds.includes(safePost.data.bookingId))+ res.status(401).json({ message: "Unauthorized" });+ else {+ const data = await prisma.attendee.create({+ data: {+ email: safePost.data.email,+ name: safePost.data.name,+ timeZone: safePost.data.timeZone,+ booking: { connect: { id: safePost.data.bookingId } },+ },+ });+ const attendee = schemaAttendeeReadPublic.parse(data);++ if (attendee) {+ res.status(201).json({+ attendee,+ message: "Attendee created successfully",+ });+ } else (error: Error) => res.status(400).json({ error });+ }+ } else {+ // @todo: check real availability times before booking+ const data = await prisma.attendee.create({data: {email: safePost.data.email,name: safePost.data.name,diff --git a/pages/api/bookings/index.ts b/pages/api/bookings/index.tsindex ab85b339cd2..47d9b80da36 100644--- a/pages/api/bookings/index.ts+++ b/pages/api/bookings/index.ts@@ -12,7 +12,7 @@ import { schemaBookingCreateBodyParams, schemaBookingReadPublic } from "@lib/valimport { schemaEventTypeReadPublic } from "@lib/validations/event-type";async function createOrlistAllBookings(- { method, body, userId }: NextApiRequest,+ { method, body, userId, isAdmin }: NextApiRequest,res: NextApiResponse<BookingsResponse | BookingResponse>) {console.log("userIduserId", userId);diff --git a/pages/api/event-types/[id].ts b/pages/api/event-types/[id].tsindex 19435a0bc69..013f9909be1 100644--- a/pages/api/event-types/[id].ts+++ b/pages/api/event-types/[id].ts@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";import { withMiddleware } from "@lib/helpers/withMiddleware";import type { EventTypeResponse } from "@lib/types";-import { isAdminGuard } from "@lib/utils/isAdmin";import { schemaEventTypeEditBodyParams, schemaEventTypeReadPublic } from "@lib/validations/event-type";import {schemaQueryIdParseInt,@@ -12,10 +11,9 @@ import {} from "@lib/validations/shared/queryIdTransformParseInt";export async function eventTypeById(- { method, query, body, userId }: NextApiRequest,+ { method, query, body, userId, isAdmin }: NextApiRequest,res: NextApiResponse<EventTypeResponse>) {- const isAdmin = await isAdminGuard(userId);const safeQuery = schemaQueryIdParseInt.safeParse(query);if (!safeQuery.success) {res.status(400).json({ message: "Your query was invalid" });diff --git a/pages/api/event-types/index.ts b/pages/api/event-types/index.tsindex bfe8c3e7ee9..dc6844e039c 100644--- a/pages/api/event-types/index.ts+++ b/pages/api/event-types/index.ts@@ -4,14 +4,12 @@ import prisma from "@calcom/prisma";import { withMiddleware } from "@lib/helpers/withMiddleware";import { EventTypeResponse, EventTypesResponse } from "@lib/types";-import { isAdminGuard } from "@lib/utils/isAdmin";import { schemaEventTypeCreateBodyParams, schemaEventTypeReadPublic } from "@lib/validations/event-type";async function createOrlistAllEventTypes(- { method, body, userId }: NextApiRequest,+ { method, body, userId, isAdmin }: NextApiRequest,res: NextApiResponse<EventTypesResponse | EventTypeResponse>) {- const isAdmin = await isAdminGuard(userId);if (method === "GET") {/*** @swaggerdiff --git a/pages/api/users/[id].ts b/pages/api/users/[id].tsindex 65b864c6526..bf70a7a7859 100644--- a/pages/api/users/[id].ts+++ b/pages/api/users/[id].ts@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";import { withMiddleware } from "@lib/helpers/withMiddleware";import type { UserResponse } from "@lib/types";-import { isAdminGuard } from "@lib/utils/isAdmin";import {schemaQueryIdParseInt,withValidQueryIdTransformParseInt,@@ -12,7 +11,7 @@ import {import { schemaUserEditBodyParams, schemaUserReadPublic } from "@lib/validations/user";export async function userById(- { method, query, body, userId }: NextApiRequest,+ { method, query, body, userId, isAdmin }: NextApiRequest,res: NextApiResponse<UserResponse>) {const safeQuery = schemaQueryIdParseInt.safeParse(query);@@ -21,7 +20,6 @@ export async function userById(res.status(400).json({ message: "Your query was invalid" });return;}- const isAdmin = await isAdminGuard(userId);// Here we only check for ownership of the user if the user is not admin, otherwise we let ADMIN's edit any userif (!isAdmin) {if (safeQuery.data.id !== userId) res.status(401).json({ message: "Unauthorized" });diff --git a/pages/api/users/index.ts b/pages/api/users/index.tsindex 3839ae21b62..d94f198ad84 100644--- a/pages/api/users/index.ts+++ b/pages/api/users/index.ts@@ -4,7 +4,6 @@ import prisma from "@calcom/prisma";import { withMiddleware } from "@lib/helpers/withMiddleware";import { UserResponse, UsersResponse } from "@lib/types";-import { isAdminGuard } from "@lib/utils/isAdmin";import { schemaUserReadPublic, schemaUserCreateBodyParams } from "@lib/validations/user";/**@@ -24,10 +23,9 @@ import { schemaUserReadPublic, schemaUserCreateBodyParams } from "@lib/validatio* description: No users were found*/async function getAllorCreateUser(- { userId, method, body }: NextApiRequest,+ { userId, method, body, isAdmin }: NextApiRequest,res: NextApiResponse<UsersResponse | UserResponse>) {- const isAdmin = await isAdminGuard(userId);if (method === "GET") {if (!isAdmin) {// If user is not ADMIN, return only his data.