diff --git a/.husky/pre-commit b/.husky/pre-commit deleted file mode 100755 index 025779ed2b..0000000000 --- a/.husky/pre-commit +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -. "$(dirname "$0")/_/husky.sh" - -yarn pre-commit diff --git a/.prettierrc.js b/.prettierrc.js deleted file mode 100644 index 246057aa0c..0000000000 --- a/.prettierrc.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("../../packages/config/prettier-preset"); diff --git a/babel.config.js b/babel.config.js deleted file mode 100644 index 2afcfd2404..0000000000 --- a/babel.config.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-typescript"], -}; diff --git a/lib/helpers/verifyApiKey.ts b/lib/helpers/verifyApiKey.ts index 008f3dc4f4..ab8115faab 100644 --- a/lib/helpers/verifyApiKey.ts +++ b/lib/helpers/verifyApiKey.ts @@ -1,34 +1,40 @@ +import type { IncomingMessage } from "http"; import { NextMiddleware } from "next-api-middleware"; import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys"; import prisma from "@calcom/prisma"; -// Used to check if the API key is not expired, could be extracted if reused. but not for now. -export const dateInPast = function (date: Date) { +/** @todo figure how to use the one from `@calcom/types`fi */ +declare module "next" { + export interface NextApiRequest extends IncomingMessage { + userId: number; + } +} + +// Used to check if the apiKey is not expired, could be extracted if reused. but not for now. +export const dateNotInPast = function (date: Date) { const now = new Date(); if (now.setHours(0, 0, 0, 0) <= date.setHours(0, 0, 0, 0)) { return true; } }; -// This verifies the API key and sets the user if it is valid. +// This verifies the apiKey and sets the user if it is valid. export const verifyApiKey: NextMiddleware = async (req, res, next) => { - if (!req.query.apiKey) res.status(401).json({ message: "No api key provided" }); + if (!req.query.apiKey) return res.status(401).json({ message: "No apiKey provided" }); // We remove the prefix from the user provided api_key. If no env set default to "cal_" const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "cal_", ""); // Hash the key again before matching against the database records. const hashedKey = hashAPIKey(strippedApiKey); // Check if the hashed api key exists in database. - await prisma.apiKey.findUnique({ where: { hashedKey } }).then(async (apiKey) => { - // If we cannot find any api key. Throw a 401 Unauthorized. - if (!apiKey) res.status(401).json({ error: "Your api key is not valid" }); - if (apiKey && apiKey.expiresAt && dateInPast(apiKey.expiresAt) && apiKey.userId) { - // Right now API Keys are user centric, we only allow resources related to this userId throughout the application. - // if the api key is not expired, and the user id is present in the database. - // Set the user in the request. as x-calcom-user-id. - res.setHeader("X-Calcom-User-ID", apiKey.userId); - // Pass the request to the next middleware. - await next(); - } - }); + const apiKey = await prisma.apiKey.findUnique({ where: { hashedKey } }); + // If we cannot find any api key. Throw a 401 Unauthorized. + if (!apiKey) return res.status(401).json({ error: "Your apiKey is not valid" }); + if (apiKey.expiresAt && dateNotInPast(apiKey.expiresAt)) { + return res.status(401).json({ error: "This apiKey is expired" }); + } + 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; + await next(); }; diff --git a/lib/types.ts b/lib/types.ts index 91af310a62..cc3f95d7e8 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -37,6 +37,7 @@ export type UsersResponse = BaseResponse & { // Team export type TeamResponse = BaseResponse & { team?: Partial; + owner?: Partial; }; export type TeamsResponse = BaseResponse & { teams?: Partial[]; diff --git a/lib/utils/getCalcomUserId.ts b/lib/utils/getCalcomUserId.ts deleted file mode 100644 index 8670bc8759..0000000000 --- a/lib/utils/getCalcomUserId.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { NextApiResponse } from "next"; - -export const getCalcomUserId = (res: NextApiResponse): number => res.getHeader("x-calcom-user-id") as number; diff --git a/lib/validations/event-type.ts b/lib/validations/event-type.ts index 113620157e..119edcb248 100644 --- a/lib/validations/event-type.ts +++ b/lib/validations/event-type.ts @@ -12,8 +12,8 @@ const schemaEventTypeRequiredParams = z.object({ }); export const schemaEventTypeBodyParams = schemaEventTypeBaseBodyParams.merge(schemaEventTypeRequiredParams); - -export const schemaEventTypePublic = EventType.omit({}); +// @NOTE: Removing locations and metadata properties before validation, add them later if required +export const schemaEventTypePublic = EventType.omit({ locations: true, metadata: true }); export const withValidEventType = withValidation({ schema: schemaEventTypeBodyParams, diff --git a/package.json b/package.json index 16dc0f9b9f..5739292e02 100644 --- a/package.json +++ b/package.json @@ -14,24 +14,17 @@ "lint-fix": "next lint --fix && prettier --write .", "test": "jest --detectOpenHandles", "type-check": "tsc --pretty --noEmit", - "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist", - "prepare": "husky install", - "pre-commit": "next lint" + "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist" }, "devDependencies": { - "@babel/core": "^7.17.8", - "@babel/preset-env": "^7.16.11", - "@babel/preset-typescript": "^7.16.7", - "@calcom/prisma": "*", "@calcom/tsconfig": "*", "@typescript-eslint/eslint-plugin": "^5.16.0", "babel-jest": "^27.5.1", - "husky": "^7.0.4", "jest": "^27.5.1", - "node-mocks-http": "^1.11.0", - "prettier": "^2.6.1" + "node-mocks-http": "^1.11.0" }, "dependencies": { + "@calcom/prisma": "*", "@sentry/nextjs": "^6.19.3", "next": "^12.1.4", "next-api-middleware": "^1.0.1", diff --git a/pages/api/attendees/[id].ts b/pages/api/attendees/[id].ts index a7b573cc87..03133bf526 100644 --- a/pages/api/attendees/[id].ts +++ b/pages/api/attendees/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { AttendeeResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaAttendeeBodyParams, schemaAttendeePublic } from "@lib/validations/attendee"; import { schemaQueryIdParseInt, @@ -93,7 +92,7 @@ export async function attendeeById(req: NextApiRequest, res: NextApiResponse booking.attendees).flat(); const attendeeIds = attendees.map((attendee) => attendee.id); // Here we make sure to only return attendee's of the user's own bookings. - if (attendeeIds.includes(safeQuery.data.id)) { + if (!attendeeIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { switch (method) { case "GET": await prisma.attendee @@ -152,7 +152,7 @@ export async function attendeeById(req: NextApiRequest, res: NextApiResponse ) { const { method } = req; - const userId = getCalcomUserId(res); + const userId = req.userId; // Here we make sure to only return attendee's of the user's own bookings. const userBookings = await prisma.booking.findMany({ where: { @@ -68,7 +67,7 @@ async function createOrlistAllAttendees( throw new Error("Invalid request body", safe.error); } const bookingId = safe.data.bookingId; - const userId = await getCalcomUserId(res); + const userId = req.userId; const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, include: { bookings: true }, @@ -77,7 +76,8 @@ async function createOrlistAllAttendees( throw new Error("User not found"); } const userBookingIds = userWithBookings.bookings.map((booking: any) => booking.id).flat(); - if (userBookingIds.includes(bookingId)) { + if (!userBookingIds.includes(bookingId)) res.status(401).json({ message: "Unauthorized" }); + else { delete safe.data.bookingId; const noBookingId = safe.data; const data = await prisma.attendee.create({ @@ -100,7 +100,7 @@ async function createOrlistAllAttendees( error, }); } - } else res.status(401).json({ message: "Unauthorized" }); + } } else res.status(405).json({ message: `Method ${method} not allowed` }); } diff --git a/pages/api/availabilities/[id].ts b/pages/api/availabilities/[id].ts index feeef587c0..7d5bfb8b91 100644 --- a/pages/api/availabilities/[id].ts +++ b/pages/api/availabilities/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { AvailabilityResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaAvailabilityBodyParams, schemaAvailabilityPublic } from "@lib/validations/availability"; import { schemaQueryIdParseInt, @@ -27,6 +26,8 @@ import { * - ApiKeyAuth: [] * tags: * - availabilities + * externalDocs: + * url: https://docs.cal.com/availability * responses: * 200: * description: OK @@ -56,6 +57,8 @@ import { * - ApiKeyAuth: [] * tags: * - availabilities + * externalDocs: + * url: https://docs.cal.com/availability * responses: * 201: * description: OK, availability edited successfuly @@ -77,6 +80,8 @@ import { * - ApiKeyAuth: [] * tags: * - availabilities + * externalDocs: + * url: https://docs.cal.com/availability * responses: * 201: * description: OK, availability removed successfuly @@ -91,10 +96,11 @@ export async function availabilityById(req: NextApiRequest, res: NextApiResponse const safeQuery = schemaQueryIdParseInt.safeParse(query); const safeBody = schemaAvailabilityBodyParams.safeParse(body); if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error); - const userId = await getCalcomUserId(res); + const userId = req.userId; const data = await prisma.availability.findMany({ where: { userId } }); const availabiltiesIds = data.map((availability) => availability.id); - if (availabiltiesIds.includes(safeQuery.data.id)) { + if (!availabiltiesIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { switch (method) { case "GET": await prisma.availability @@ -137,8 +143,6 @@ export async function availabilityById(req: NextApiRequest, res: NextApiResponse res.status(405).json({ message: "Method not allowed" }); break; } - } else { - res.status(401).json({ message: "Unauthorized" }); } } diff --git a/pages/api/availabilities/index.ts b/pages/api/availabilities/index.ts index 558b948d30..a6310059f7 100644 --- a/pages/api/availabilities/index.ts +++ b/pages/api/availabilities/index.ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { AvailabilityResponse, AvailabilitiesResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaAvailabilityBodyParams, schemaAvailabilityPublic } from "@lib/validations/availability"; /** @@ -16,6 +15,8 @@ import { schemaAvailabilityBodyParams, schemaAvailabilityPublic } from "@lib/val * - ApiKeyAuth: [] * tags: * - availabilities + * externalDocs: + * url: https://docs.cal.com/availability * responses: * 200: * description: OK @@ -29,6 +30,8 @@ import { schemaAvailabilityBodyParams, schemaAvailabilityPublic } from "@lib/val * - ApiKeyAuth: [] * tags: * - availabilities + * externalDocs: + * url: https://docs.cal.com/availability * responses: * 201: * description: OK, availability created @@ -43,7 +46,7 @@ async function createOrlistAllAvailabilities( res: NextApiResponse ) { const { method } = req; - const userId = await getCalcomUserId(res); + const userId = req.userId; if (method === "GET") { const data = await prisma.availability.findMany({ where: { userId } }); diff --git a/pages/api/booking-references/[id].ts b/pages/api/booking-references/[id].ts index 3067dc3c15..1644041b2f 100644 --- a/pages/api/booking-references/[id].ts +++ b/pages/api/booking-references/[id].ts @@ -5,7 +5,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { BookingReferenceResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaBookingReferenceBodyParams, schemaBookingReferencePublic, @@ -98,7 +97,7 @@ export async function bookingReferenceById( const safeQuery = schemaQueryIdParseInt.safeParse(query); const safeBody = schemaBookingReferenceBodyParams.safeParse(body); if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error); - const userId = await getCalcomUserId(res); + const userId = req.userId; const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, include: { bookings: true }, diff --git a/pages/api/booking-references/index.ts b/pages/api/booking-references/index.ts index d256936ce5..74ae942dd2 100644 --- a/pages/api/booking-references/index.ts +++ b/pages/api/booking-references/index.ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { BookingReferenceResponse, BookingReferencesResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaBookingReferenceBodyParams, schemaBookingReferencePublic, @@ -46,7 +45,7 @@ async function createOrlistAllBookingReferences( res: NextApiResponse ) { const { method } = req; - const userId = await getCalcomUserId(res); + const userId = req.userId; const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, include: { bookings: true }, @@ -72,7 +71,7 @@ async function createOrlistAllBookingReferences( } // const booking_reference = schemaBookingReferencePublic.parse(data); - const userId = await getCalcomUserId(res); + const userId = req.userId; const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, include: { bookings: true }, @@ -81,7 +80,8 @@ async function createOrlistAllBookingReferences( throw new Error("User not found"); } const userBookingIds = userWithBookings.bookings.map((booking: any) => booking.id).flat(); - if (userBookingIds.includes(safe.data.bookingId)) { + if (!userBookingIds.includes(safe.data.bookingId)) res.status(401).json({ message: "Unauthorized" }); + else { const booking_reference = await prisma.bookingReference.create({ data: { ...safe.data }, }); @@ -97,7 +97,7 @@ async function createOrlistAllBookingReferences( error, }); } - } else res.status(401).json({ message: "Unauthorized" }); + } } else res.status(405).json({ message: `Method ${method} not allowed` }); } diff --git a/pages/api/bookings/[id].ts b/pages/api/bookings/[id].ts index e3e56b9a36..9172b7dc90 100644 --- a/pages/api/bookings/[id].ts +++ b/pages/api/bookings/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { BookingResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaBookingBodyParams, schemaBookingPublic } from "@lib/validations/booking"; import { schemaQueryIdParseInt, @@ -91,14 +90,15 @@ export async function bookingById(req: NextApiRequest, res: NextApiResponse booking.id).flat(); - if (userBookingIds.includes(safeQuery.data.id)) { + if (!userBookingIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { switch (method) { case "GET": await prisma.booking @@ -152,7 +152,7 @@ export async function bookingById(req: NextApiRequest, res: NextApiResponse ) { const { method } = req; - const userId = await getCalcomUserId(res); + const userId = req.userId; if (method === "GET") { const data = await prisma.booking.findMany({ where: { userId } }); diff --git a/pages/api/daily-event-references/[id].ts b/pages/api/daily-event-references/[id].ts index 17d6ced278..b8bb8dc88c 100644 --- a/pages/api/daily-event-references/[id].ts +++ b/pages/api/daily-event-references/[id].ts @@ -96,52 +96,70 @@ export async function dailyEventReferenceById( const safeQuery = schemaQueryIdParseInt.safeParse(query); const safeBody = schemaDailyEventReferenceBodyParams.safeParse(body); if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error); + const userId = req.userId; + const userBookings = await prisma.booking.findMany({ where: { userId } }); + const userBookingIds = userBookings.map((booking) => booking.id); + const userBookingDailyEventReferences = await prisma.dailyEventReference.findMany({ + where: { bookingId: { in: userBookingIds } }, + }); + const userBookingDailyEventReferenceIds = userBookingDailyEventReferences.map( + (dailyEventReference) => dailyEventReference.id + ); + if (!userBookingDailyEventReferenceIds.includes(safeQuery.data.id)) + res.status(401).json({ message: "Unauthorized" }); + else { + switch (method) { + case "GET": + await prisma.dailyEventReference + .findUnique({ where: { id: safeQuery.data.id } }) + .then((data) => schemaDailyEventReferencePublic.parse(data)) + .then((daily_event_reference) => res.status(200).json({ daily_event_reference })) + .catch((error: Error) => + res.status(404).json({ + message: `DailyEventReference with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - switch (method) { - case "GET": - await prisma.dailyEventReference - .findUnique({ where: { id: safeQuery.data.id } }) - .then((data) => schemaDailyEventReferencePublic.parse(data)) - .then((daily_event_reference) => res.status(200).json({ daily_event_reference })) - .catch((error: Error) => - res - .status(404) - .json({ message: `DailyEventReference with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "PATCH": + if (!safeBody.success) { + throw new Error("Invalid request body"); + } + await prisma.dailyEventReference + .update({ where: { id: safeQuery.data.id }, data: safeBody.data }) + .then((data) => schemaDailyEventReferencePublic.parse(data)) + .then((daily_event_reference) => res.status(200).json({ daily_event_reference })) + .catch((error: Error) => + res.status(404).json({ + message: `DailyEventReference with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "PATCH": - if (!safeBody.success) throw new Error("Invalid request body"); - await prisma.dailyEventReference - .update({ - where: { id: safeQuery.data.id }, - data: safeBody.data, - }) - .then((data) => schemaDailyEventReferencePublic.parse(data)) - .then((daily_event_reference) => res.status(200).json({ daily_event_reference })) - .catch((error: Error) => - res - .status(404) - .json({ message: `DailyEventReference with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "DELETE": + await prisma.dailyEventReference + .delete({ + where: { id: safeQuery.data.id }, + }) + .then(() => + res.status(200).json({ + message: `DailyEventReference with id: ${safeQuery.data.id} deleted`, + }) + ) + .catch((error: Error) => + res.status(404).json({ + message: `DailyEventReference with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "DELETE": - await prisma.dailyEventReference - .delete({ where: { id: safeQuery.data.id } }) - .then(() => - res.status(200).json({ message: `DailyEventReference with id: ${safeQuery.data.id} deleted` }) - ) - .catch((error: Error) => - res - .status(404) - .json({ message: `DailyEventReference with id: ${safeQuery.data.id} not found`, error }) - ); - break; - - default: - res.status(405).json({ message: "Method not allowed" }); - break; + default: + res.status(405).json({ message: "Method not allowed" }); + break; + } } } diff --git a/pages/api/daily-event-references/index.ts b/pages/api/daily-event-references/index.ts index aa60482bb1..7b216d0040 100644 --- a/pages/api/daily-event-references/index.ts +++ b/pages/api/daily-event-references/index.ts @@ -17,7 +17,7 @@ import { * security: * - ApiKeyAuth: [] * tags: - * - daily-event-reference + * - daily-event-references * responses: * 200: * description: OK @@ -30,7 +30,7 @@ import { * security: * - ApiKeyAuth: [] * tags: - * - daily-event-reference + * - daily-event-references * responses: * 201: * description: OK, daily event reference created @@ -45,8 +45,14 @@ async function createOrlistAllDailyEventReferences( res: NextApiResponse ) { const { method } = req; + const userId = req.userId; + const userBookings = await prisma.booking.findMany({ where: { userId } }); + const userBookingIds = userBookings.map((booking) => booking.id); + if (method === "GET") { - const data = await prisma.dailyEventReference.findMany(); + const data = await prisma.dailyEventReference.findMany({ + where: { bookingId: { in: userBookingIds } }, + }); const daily_event_references = data.map((dailyEventReference) => schemaDailyEventReferencePublic.parse(dailyEventReference) ); diff --git a/pages/api/destination-calendars/[id].ts b/pages/api/destination-calendars/[id].ts index ef7712e525..2f643d4120 100644 --- a/pages/api/destination-calendars/[id].ts +++ b/pages/api/destination-calendars/[id].ts @@ -96,52 +96,65 @@ export async function destionationCalendarById( const safeQuery = schemaQueryIdParseInt.safeParse(query); const safeBody = schemaDestinationCalendarBodyParams.safeParse(body); if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error); + const userId = req.userId; + const data = await prisma.destinationCalendar.findMany({ where: { userId } }); + const userDestinationCalendars = data.map((destinationCalendar) => destinationCalendar.id); + // FIXME: Should we also check ownership of bokingId and eventTypeId to avoid users cross-pollinating other users calendars. + // On a related note, moving from sequential integer IDs to UUIDs would be a good idea. and maybe help avoid having this problem. + if (userDestinationCalendars.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { + switch (method) { + case "GET": + await prisma.destinationCalendar + .findUnique({ where: { id: safeQuery.data.id } }) + .then((data) => schemaDestinationCalendarPublic.parse(data)) + .then((destination_calendar) => res.status(200).json({ destination_calendar })) + .catch((error: Error) => + res.status(404).json({ + message: `DestinationCalendar with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - switch (method) { - case "GET": - await prisma.destinationCalendar - .findUnique({ where: { id: safeQuery.data.id } }) - .then((data) => schemaDestinationCalendarPublic.parse(data)) - .then((destination_calendar) => res.status(200).json({ destination_calendar })) - .catch((error: Error) => - res - .status(404) - .json({ message: `DestinationCalendar with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "PATCH": + if (!safeBody.success) { + throw new Error("Invalid request body"); + } + await prisma.destinationCalendar + .update({ where: { id: safeQuery.data.id }, data: safeBody.data }) + .then((data) => schemaDestinationCalendarPublic.parse(data)) + .then((destination_calendar) => res.status(200).json({ destination_calendar })) + .catch((error: Error) => + res.status(404).json({ + message: `DestinationCalendar with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "PATCH": - if (!safeBody.success) throw new Error("Invalid request body"); - await prisma.destinationCalendar - .update({ - where: { id: safeQuery.data.id }, - data: safeBody.data, - }) - .then((data) => schemaDestinationCalendarPublic.parse(data)) - .then((destination_calendar) => res.status(200).json({ destination_calendar })) - .catch((error: Error) => - res - .status(404) - .json({ message: `DestinationCalendar with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "DELETE": + await prisma.destinationCalendar + .delete({ + where: { id: safeQuery.data.id }, + }) + .then(() => + res.status(200).json({ + message: `DestinationCalendar with id: ${safeQuery.data.id} deleted`, + }) + ) + .catch((error: Error) => + res.status(404).json({ + message: `DestinationCalendar with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "DELETE": - await prisma.destinationCalendar - .delete({ where: { id: safeQuery.data.id } }) - .then(() => - res.status(200).json({ message: `DestinationCalendar with id: ${safeQuery.data.id} deleted` }) - ) - .catch((error: Error) => - res - .status(404) - .json({ message: `DestinationCalendar with id: ${safeQuery.data.id} not found`, error }) - ); - break; - - default: - res.status(405).json({ message: "Method not allowed" }); - break; + default: + res.status(405).json({ message: "Method not allowed" }); + break; + } } } diff --git a/pages/api/destination-calendars/index.ts b/pages/api/destination-calendars/index.ts index 3980b3e203..b3bdcaab57 100644 --- a/pages/api/destination-calendars/index.ts +++ b/pages/api/destination-calendars/index.ts @@ -45,8 +45,10 @@ async function createOrlistAllDestinationCalendars( res: NextApiResponse ) { const { method } = req; + const userId = req.userId; + if (method === "GET") { - const data = await prisma.destinationCalendar.findMany(); + const data = await prisma.destinationCalendar.findMany({ where: { userId } }); const destination_calendars = data.map((destinationCalendar) => schemaDestinationCalendarPublic.parse(destinationCalendar) ); @@ -61,7 +63,7 @@ async function createOrlistAllDestinationCalendars( const safe = schemaDestinationCalendarBodyParams.safeParse(req.body); if (!safe.success) throw new Error("Invalid request body"); - const data = await prisma.destinationCalendar.create({ data: safe.data }); + const data = await prisma.destinationCalendar.create({ data: { ...safe.data, userId } }); const destination_calendar = schemaDestinationCalendarPublic.parse(data); if (destination_calendar) diff --git a/pages/api/event-type-custom-inputs/[id].ts b/pages/api/event-type-custom-inputs/[id].ts index d9dd21d112..4df7114cef 100644 --- a/pages/api/event-type-custom-inputs/[id].ts +++ b/pages/api/event-type-custom-inputs/[id].ts @@ -93,46 +93,70 @@ async function eventTypeById(req: NextApiRequest, res: NextApiResponse eventType.id); + const userEventTypeCustomInputs = await prisma.eventTypeCustomInput.findMany({ + where: { eventType: userEventTypes }, + }); + const userEventTypeCustomInputIds = userEventTypeCustomInputs.map( + (eventTypeCustomInput) => eventTypeCustomInput.id + ); + if (!userEventTypeCustomInputIds.includes(safeQuery.data.id)) + res.status(401).json({ message: "Unauthorized" }); + else { + switch (method) { + case "GET": + await prisma.eventTypeCustomInput + .findUnique({ where: { id: safeQuery.data.id } }) + .then((data) => schemaEventTypeCustomInputPublic.parse(data)) + .then((event_type_custom_input) => res.status(200).json({ event_type_custom_input })) + .catch((error: Error) => + res.status(404).json({ + message: `EventType with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - switch (method) { - case "GET": - await prisma.eventTypeCustomInput - .findUnique({ where: { id: safeQuery.data.id } }) - .then((data) => schemaEventTypeCustomInputPublic.parse(data)) - .then((event_type_custom_input) => res.status(200).json({ event_type_custom_input })) - .catch((error: Error) => - res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "PATCH": + if (!safeBody.success) { + throw new Error("Invalid request body"); + } + await prisma.eventTypeCustomInput + .update({ where: { id: safeQuery.data.id }, data: safeBody.data }) + .then((data) => schemaEventTypeCustomInputPublic.parse(data)) + .then((event_type_custom_input) => res.status(200).json({ event_type_custom_input })) + .catch((error: Error) => + res.status(404).json({ + message: `EventType with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "PATCH": - if (!safeBody.success) throw new Error("Invalid request body"); - await prisma.eventTypeCustomInput - .update({ - where: { id: safeQuery.data.id }, - data: safeBody.data, - }) - .then((data) => schemaEventTypeCustomInputPublic.parse(data)) - .then((event_type_custom_input) => res.status(200).json({ event_type_custom_input })) - .catch((error: Error) => - res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "DELETE": + await prisma.eventTypeCustomInput + .delete({ + where: { id: safeQuery.data.id }, + }) + .then(() => + res.status(200).json({ + message: `CustomInputEventType with id: ${safeQuery.data.id} deleted`, + }) + ) + .catch((error: Error) => + res.status(404).json({ + message: `EventType with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "DELETE": - await prisma.eventTypeCustomInput - .delete({ where: { id: safeQuery.data.id } }) - .then(() => - res.status(200).json({ message: `CustomInputEventType with id: ${safeQuery.data.id} deleted` }) - ) - .catch((error: Error) => - res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error }) - ); - break; - - default: - res.status(405).json({ message: "Method not allowed" }); - break; + default: + res.status(405).json({ message: "Method not allowed" }); + break; + } } } diff --git a/pages/api/event-type-custom-inputs/index.ts b/pages/api/event-type-custom-inputs/index.ts index 806d3ca91e..5b3b249ab4 100644 --- a/pages/api/event-type-custom-inputs/index.ts +++ b/pages/api/event-type-custom-inputs/index.ts @@ -45,8 +45,12 @@ async function createOrlistAllEventTypeCustomInputs( res: NextApiResponse ) { const { method } = req; + const userId = req.userId; + const data = await prisma.eventType.findMany({ where: { userId } }); + const userEventTypes = data.map((eventType) => eventType.id); + if (method === "GET") { - const data = await prisma.eventTypeCustomInput.findMany(); + const data = await prisma.eventTypeCustomInput.findMany({ where: { eventType: userEventTypes } }); const event_type_custom_inputs = data.map((eventTypeCustomInput) => schemaEventTypeCustomInputPublic.parse(eventTypeCustomInput) ); @@ -60,13 +64,25 @@ async function createOrlistAllEventTypeCustomInputs( } else if (method === "POST") { const safe = schemaEventTypeCustomInputBodyParams.safeParse(req.body); if (!safe.success) throw new Error("Invalid request body"); - - const data = await prisma.eventTypeCustomInput.create({ data: safe.data }); - const event_type_custom_input = schemaEventTypeCustomInputPublic.parse(data); - - if (event_type_custom_input) - res.status(201).json({ event_type_custom_input, message: "EventTypeCustomInput created successfully" }); - else + // Since we're supporting a create or connect relation on eventType, we need to treat them differently + // When using connect on event type, check if userId is the owner of the event + if (safe.data.eventType.connect && !userEventTypes.includes(safe.data.eventType.connect.id as number)) { + const data = await prisma.eventTypeCustomInput.create({ data: { ...safe.data } }); + const event_type_custom_input = schemaEventTypeCustomInputPublic.parse(data); + if (event_type_custom_input) + res + .status(201) + .json({ event_type_custom_input, message: "EventTypeCustomInput created successfully" }); + // When creating, no need + // FIXME: we might want to pass userId to the new created/linked eventType, though. + } else if (safe.data.eventType.create) { + const data = await prisma.eventTypeCustomInput.create({ data: { ...safe.data } }); + const event_type_custom_input = schemaEventTypeCustomInputPublic.parse(data); + if (event_type_custom_input) + res + .status(201) + .json({ event_type_custom_input, message: "EventTypeCustomInput created successfully" }); + } else (error: Error) => res.status(400).json({ message: "Could not create new eventTypeCustomInput", diff --git a/pages/api/event-types/[id].ts b/pages/api/event-types/[id].ts index 410cbbb5af..94dd09dee2 100644 --- a/pages/api/event-types/[id].ts +++ b/pages/api/event-types/[id].ts @@ -26,6 +26,8 @@ import { * - ApiKeyAuth: [] * tags: * - event-types + * externalDocs: + * url: https://docs.cal.com/event-types * responses: * 200: * description: OK @@ -55,6 +57,8 @@ import { * - ApiKeyAuth: [] * tags: * - event-types + * externalDocs: + * url: https://docs.cal.com/event-types * responses: * 201: * description: OK, eventType edited successfuly @@ -76,6 +80,8 @@ import { * - ApiKeyAuth: [] * tags: * - event-types + * externalDocs: + * url: https://docs.cal.com/event-types * responses: * 201: * description: OK, eventType removed successfuly @@ -90,44 +96,61 @@ export async function eventTypeById(req: NextApiRequest, res: NextApiResponse eventType.id); + if (!userEventTypes.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { + switch (method) { + case "GET": + await prisma.eventType + .findUnique({ where: { id: safeQuery.data.id } }) + .then((data) => schemaEventTypePublic.parse(data)) + .then((event_type) => res.status(200).json({ event_type })) + .catch((error: Error) => + res.status(404).json({ + message: `EventType with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - switch (method) { - case "GET": - await prisma.eventType - .findUnique({ where: { id: safeQuery.data.id } }) - .then((data) => schemaEventTypePublic.parse(data)) - .then((event_type) => res.status(200).json({ event_type })) - .catch((error: Error) => - res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "PATCH": + if (!safeBody.success) { + throw new Error("Invalid request body"); + } + await prisma.eventType + .update({ where: { id: safeQuery.data.id }, data: safeBody.data }) + .then((data) => schemaEventTypePublic.parse(data)) + .then((event_type) => res.status(200).json({ event_type })) + .catch((error: Error) => + res.status(404).json({ + message: `EventType with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "PATCH": - if (!safeBody.success) throw new Error("Invalid request body"); - await prisma.eventType - .update({ - where: { id: safeQuery.data.id }, - data: safeBody.data, - }) - .then((data) => schemaEventTypePublic.parse(data)) - .then((event_type) => res.status(200).json({ event_type })) - .catch((error: Error) => - res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "DELETE": + await prisma.eventType + .delete({ where: { id: safeQuery.data.id } }) + .then(() => + res.status(200).json({ + message: `EventType with id: ${safeQuery.data.id} deleted`, + }) + ) + .catch((error: Error) => + res.status(404).json({ + message: `EventType with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "DELETE": - await prisma.eventType - .delete({ where: { id: safeQuery.data.id } }) - .then(() => res.status(200).json({ message: `EventType with id: ${safeQuery.data.id} deleted` })) - .catch((error: Error) => - res.status(404).json({ message: `EventType with id: ${safeQuery.data.id} not found`, error }) - ); - break; - - default: - res.status(405).json({ message: "Method not allowed" }); - break; + default: + res.status(405).json({ message: "Method not allowed" }); + break; + } } } diff --git a/pages/api/event-types/index.ts b/pages/api/event-types/index.ts index 7f04a6a3de..3135d9e866 100644 --- a/pages/api/event-types/index.ts +++ b/pages/api/event-types/index.ts @@ -15,6 +15,8 @@ import { schemaEventTypeBodyParams, schemaEventTypePublic } from "@lib/validatio * - ApiKeyAuth: [] * tags: * - event-types + * externalDocs: + * url: https://docs.cal.com/event-types * responses: * 200: * description: OK @@ -28,6 +30,8 @@ import { schemaEventTypeBodyParams, schemaEventTypePublic } from "@lib/validatio * - ApiKeyAuth: [] * tags: * - event-types + * externalDocs: + * url: https://docs.cal.com/event-types * responses: * 201: * description: OK, event type created @@ -42,8 +46,10 @@ async function createOrlistAllEventTypes( res: NextApiResponse ) { const { method } = req; + const userId = req.userId; + if (method === "GET") { - const data = await prisma.eventType.findMany(); + const data = await prisma.eventType.findMany({ where: { userId } }); const event_types = data.map((eventType) => schemaEventTypePublic.parse(eventType)); if (event_types) res.status(200).json({ event_types }); else @@ -56,7 +62,7 @@ async function createOrlistAllEventTypes( const safe = schemaEventTypeBodyParams.safeParse(req.body); if (!safe.success) throw new Error("Invalid request body"); - const data = await prisma.eventType.create({ data: safe.data }); + const data = await prisma.eventType.create({ data: { ...safe.data, userId } }); const event_type = schemaEventTypePublic.parse(data); if (data) res.status(201).json({ event_type, message: "EventType created successfully" }); diff --git a/pages/api/memberships/[id].ts b/pages/api/memberships/[id].ts index 2fbb14bcdb..acb8f03c0c 100644 --- a/pages/api/memberships/[id].ts +++ b/pages/api/memberships/[id].ts @@ -106,47 +106,82 @@ export async function membershipById(req: NextApiRequest, res: NextApiResponse schemaMembershipPublic.parse(data)) + .then((membership) => res.status(200).json({ membership })) + .catch((error: Error) => + res.status(404).json({ + message: `Membership with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - switch (method) { - case "GET": - await prisma.membership - .findUnique({ where: { userId_teamId: { userId: parseInt(userId), teamId: parseInt(teamId) } } }) - .then((data) => schemaMembershipPublic.parse(data)) - .then((membership) => res.status(200).json({ membership })) - .catch((error: Error) => - res.status(404).json({ message: `Membership with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "PATCH": + if (!safeBody.success) { + throw new Error("Invalid request body"); + } + await prisma.membership + .update({ + where: { + userId_teamId: { + userId: userId, + teamId: parseInt(teamId), + }, + }, + data: safeBody.data, + }) + .then((data) => schemaMembershipPublic.parse(data)) + .then((membership) => res.status(200).json({ membership })) + .catch((error: Error) => + res.status(404).json({ + message: `Membership with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "PATCH": - if (!safeBody.success) throw new Error("Invalid request body"); - await prisma.membership - .update({ - where: { userId_teamId: { userId: parseInt(userId), teamId: parseInt(teamId) } }, - data: safeBody.data, - }) - .then((data) => schemaMembershipPublic.parse(data)) - .then((membership) => res.status(200).json({ membership })) - .catch((error: Error) => - res.status(404).json({ message: `Membership with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "DELETE": + await prisma.membership + .delete({ + where: { + userId_teamId: { + userId: userId, + teamId: parseInt(teamId), + }, + }, + }) + .then(() => + res.status(200).json({ + message: `Membership with id: ${safeQuery.data.id} deleted successfully`, + }) + ) + .catch((error: Error) => + res.status(404).json({ + message: `Membership with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "DELETE": - await prisma.membership - .delete({ where: { userId_teamId: { userId: parseInt(userId), teamId: parseInt(teamId) } } }) - .then(() => - res.status(200).json({ message: `Membership with id: ${safeQuery.data.id} deleted successfully` }) - ) - .catch((error: Error) => - res.status(404).json({ message: `Membership with id: ${safeQuery.data.id} not found`, error }) - ); - break; - - default: - res.status(405).json({ message: "Method not allowed" }); - break; + default: + res.status(405).json({ message: "Method not allowed" }); + break; + } } } diff --git a/pages/api/memberships/index.ts b/pages/api/memberships/index.ts index 85c2ddced1..6402ac8ca4 100644 --- a/pages/api/memberships/index.ts +++ b/pages/api/memberships/index.ts @@ -42,8 +42,9 @@ async function createOrlistAllMemberships( res: NextApiResponse ) { const { method } = req; + const userId = req.userId; if (method === "GET") { - const data = await prisma.membership.findMany(); + const data = await prisma.membership.findMany({ where: { userId } }); const memberships = data.map((membership) => schemaMembershipPublic.parse(membership)); if (memberships) res.status(200).json({ memberships }); else @@ -56,7 +57,7 @@ async function createOrlistAllMemberships( const safe = schemaMembershipBodyParams.safeParse(req.body); if (!safe.success) throw new Error("Invalid request body"); - const data = await prisma.membership.create({ data: safe.data }); + const data = await prisma.membership.create({ data: { ...safe.data, userId } }); const membership = schemaMembershipPublic.parse(data); if (membership) res.status(201).json({ membership, message: "Membership created successfully" }); diff --git a/pages/api/payments/[id].ts b/pages/api/payments/[id].ts index f196b4cac0..3f23750b2a 100644 --- a/pages/api/payments/[id].ts +++ b/pages/api/payments/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { PaymentResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaPaymentPublic } from "@lib/validations/payment"; import { schemaQueryIdParseInt, @@ -38,7 +37,7 @@ import { export async function paymentById(req: NextApiRequest, res: NextApiResponse) { const { method, query } = req; const safeQuery = schemaQueryIdParseInt.safeParse(query); - const userId = await getCalcomUserId(res); + const userId = req.userId; if (safeQuery.success && method === "GET") { const userWithBookings = await prisma.user.findUnique({ @@ -49,10 +48,10 @@ export async function paymentById(req: NextApiRequest, res: NextApiResponse schemaPaymentPublic.parse(data)) .then((payment) => { - if (userWithBookings?.bookings.map((b) => b.id).includes(payment.bookingId)) { - res.status(200).json({ payment }); - } else { + if (!userWithBookings?.bookings.map((b) => b.id).includes(payment.bookingId)) { res.status(401).json({ message: "Unauthorized" }); + } else { + res.status(200).json({ payment }); } }) .catch((error: Error) => diff --git a/pages/api/payments/index.ts b/pages/api/payments/index.ts index 20028df180..827bd68340 100644 --- a/pages/api/payments/index.ts +++ b/pages/api/payments/index.ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { PaymentsResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaPaymentPublic } from "@lib/validations/payment"; /** @@ -24,8 +23,8 @@ import { schemaPaymentPublic } from "@lib/validations/payment"; * 404: * description: No payments were found */ -async function allPayments(_: NextApiRequest, res: NextApiResponse) { - const userId = await getCalcomUserId(res); +async function allPayments(req: NextApiRequest, res: NextApiResponse) { + const userId = req.userId; const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, diff --git a/pages/api/reminder-mails/[id].ts b/pages/api/reminder-mails/[id].ts deleted file mode 100644 index e6627ef7b9..0000000000 --- a/pages/api/reminder-mails/[id].ts +++ /dev/null @@ -1,136 +0,0 @@ -import type { NextApiRequest, NextApiResponse } from "next"; - -import prisma from "@calcom/prisma"; - -import { withMiddleware } from "@lib/helpers/withMiddleware"; -import type { ReminderMailResponse } from "@lib/types"; -import { schemaReminderMailBodyParams, schemaReminderMailPublic } from "@lib/validations/reminder-mail"; -import { - schemaQueryIdParseInt, - withValidQueryIdTransformParseInt, -} from "@lib/validations/shared/queryIdTransformParseInt"; - -/** - * @swagger - * /v1/reminder-mails/{id}: - * get: - * summary: Get a reminderMail by ID - * parameters: - * - in: path - * name: id - * schema: - * type: integer - * required: true - * description: Numeric ID of the reminderMail to get - * security: - * - ApiKeyAuth: [] - * tags: - * - reminder-mails - * responses: - * 200: - * description: OK - * 401: - * description: Authorization information is missing or invalid. - * 404: - * description: ReminderMail was not found - * patch: - * summary: Edit an existing reminderMail - * consumes: - * - application/json - * parameters: - * - in: body - * name: reminderMail - * description: The reminderMail to edit - * schema: - * type: object - * $ref: '#/components/schemas/ReminderMail' - * required: true - * - in: path - * name: id - * schema: - * type: integer - * required: true - * description: Numeric ID of the reminderMail to edit - * security: - * - ApiKeyAuth: [] - * tags: - * - reminder-mails - * responses: - * 201: - * description: OK, reminderMail edited successfuly - * model: ReminderMail - * 400: - * description: Bad request. ReminderMail body is invalid. - * 401: - * description: Authorization information is missing or invalid. - * delete: - * summary: Remove an existing reminderMail - * parameters: - * - in: path - * name: id - * schema: - * type: integer - * required: true - * description: Numeric ID of the reminderMail to delete - * security: - * - ApiKeyAuth: [] - * tags: - * - reminder-mails - * responses: - * 201: - * description: OK, reminderMail removed successfuly - * model: ReminderMail - * 400: - * description: Bad request. ReminderMail id is invalid. - * 401: - * description: Authorization information is missing or invalid. - */ -export async function reminderMailById(req: NextApiRequest, res: NextApiResponse) { - const { method, query, body } = req; - const safeQuery = schemaQueryIdParseInt.safeParse(query); - const safeBody = schemaReminderMailBodyParams.safeParse(body); - if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error); - - switch (method) { - case "GET": - await prisma.reminderMail - .findUnique({ where: { id: safeQuery.data.id } }) - .then((data) => schemaReminderMailPublic.parse(data)) - .then((reminder_mail) => res.status(200).json({ reminder_mail })) - .catch((error: Error) => - res.status(404).json({ message: `ReminderMail with id: ${safeQuery.data.id} not found`, error }) - ); - break; - - case "PATCH": - if (!safeBody.success) throw new Error("Invalid request body"); - await prisma.reminderMail - .update({ - where: { id: safeQuery.data.id }, - data: safeBody.data, - }) - .then((reminderMail) => schemaReminderMailPublic.parse(reminderMail)) - .then((reminder_mail) => res.status(200).json({ reminder_mail })) - .catch((error: Error) => - res.status(404).json({ message: `ReminderMail with id: ${safeQuery.data.id} not found`, error }) - ); - break; - - case "DELETE": - await prisma.reminderMail - .delete({ where: { id: safeQuery.data.id } }) - .then(() => - res.status(200).json({ message: `ReminderMail with id: ${safeQuery.data.id} deleted successfully` }) - ) - .catch((error: Error) => - res.status(404).json({ message: `ReminderMail with id: ${safeQuery.data.id} not found`, error }) - ); - break; - - default: - res.status(405).json({ message: "Method not allowed" }); - break; - } -} - -export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(reminderMailById)); diff --git a/pages/api/reminder-mails/index.ts b/pages/api/reminder-mails/index.ts deleted file mode 100644 index 22c4f63dab..0000000000 --- a/pages/api/reminder-mails/index.ts +++ /dev/null @@ -1,76 +0,0 @@ -import type { NextApiRequest, NextApiResponse } from "next"; - -import prisma from "@calcom/prisma"; - -import { withMiddleware } from "@lib/helpers/withMiddleware"; -import { ReminderMailResponse, ReminderMailsResponse } from "@lib/types"; -import { - schemaReminderMailBodyParams, - schemaReminderMailPublic, - withValidReminderMail, -} from "@lib/validations/reminder-mail"; - -/** - * @swagger - * /v1/reminder-mails: - * get: - * summary: Get all reminder mails - * security: - * - ApiKeyAuth: [] - * tags: - * - reminder-mails - * responses: - * 200: - * description: OK - * 401: - * description: Authorization information is missing or invalid. - * 404: - * description: No reminder mails were found - * post: - * summary: Creates a new reminder mail - * security: - * - ApiKeyAuth: [] - * tags: - * - reminder-mails - * responses: - * 201: - * description: OK, reminder mail created - * model: ReminderMail - * 400: - * description: Bad request. ReminderMail body is invalid. - * 401: - * description: Authorization information is missing or invalid. - */ -async function createOrlistAllReminderMails( - req: NextApiRequest, - res: NextApiResponse -) { - const { method } = req; - if (method === "GET") { - const data = await prisma.reminderMail.findMany(); - const reminder_mails = data.map((reminderMail) => schemaReminderMailPublic.parse(reminderMail)); - if (reminder_mails) res.status(200).json({ reminder_mails }); - else - (error: Error) => - res.status(404).json({ - message: "No ReminderMails were found", - error, - }); - } else if (method === "POST") { - const safe = schemaReminderMailBodyParams.safeParse(req.body); - if (!safe.success) throw new Error("Invalid request body"); - - const data = await prisma.reminderMail.create({ data: safe.data }); - const reminder_mail = schemaReminderMailPublic.parse(data); - - if (reminder_mail) res.status(201).json({ reminder_mail, message: "reminder mail created successfully" }); - else - (error: Error) => - res.status(400).json({ - message: "could not create new reminder mail", - error, - }); - } else res.status(405).json({ message: `Method ${method} not allowed` }); -} - -export default withMiddleware("HTTP_GET_OR_POST")(withValidReminderMail(createOrlistAllReminderMails)); diff --git a/pages/api/schedules/[id].ts b/pages/api/schedules/[id].ts index eb87d13949..a8fa501412 100644 --- a/pages/api/schedules/[id].ts +++ b/pages/api/schedules/[id].ts @@ -90,46 +90,61 @@ export async function scheduleById(req: NextApiRequest, res: NextApiResponse schedule.id); + if (!userScheduleIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { + switch (method) { + case "GET": + await prisma.schedule + .findUnique({ where: { id: safeQuery.data.id } }) + .then((data) => schemaSchedulePublic.parse(data)) + .then((schedule) => res.status(200).json({ schedule })) + .catch((error: Error) => + res.status(404).json({ + message: `Schedule with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - switch (method) { - case "GET": - await prisma.schedule - .findUnique({ where: { id: safeQuery.data.id } }) - .then((data) => schemaSchedulePublic.parse(data)) - .then((schedule) => res.status(200).json({ schedule })) - .catch((error: Error) => - res.status(404).json({ message: `Schedule with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "PATCH": + if (!safeBody.success) { + throw new Error("Invalid request body"); + } + await prisma.schedule + .update({ where: { id: safeQuery.data.id }, data: safeBody.data }) + .then((data) => schemaSchedulePublic.parse(data)) + .then((schedule) => res.status(200).json({ schedule })) + .catch((error: Error) => + res.status(404).json({ + message: `Schedule with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "PATCH": - if (!safeBody.success) throw new Error("Invalid request body"); - await prisma.schedule - .update({ - where: { id: safeQuery.data.id }, - data: safeBody.data, - }) - .then((data) => schemaSchedulePublic.parse(data)) - .then((schedule) => res.status(200).json({ schedule })) - .catch((error: Error) => - res.status(404).json({ message: `Schedule with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "DELETE": + await prisma.schedule + .delete({ where: { id: safeQuery.data.id } }) + .then(() => + res.status(200).json({ + message: `Schedule with id: ${safeQuery.data.id} deleted successfully`, + }) + ) + .catch((error: Error) => + res.status(404).json({ + message: `Schedule with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "DELETE": - await prisma.schedule - .delete({ where: { id: safeQuery.data.id } }) - .then(() => - res.status(200).json({ message: `Schedule with id: ${safeQuery.data.id} deleted successfully` }) - ) - .catch((error: Error) => - res.status(404).json({ message: `Schedule with id: ${safeQuery.data.id} not found`, error }) - ); - break; - - default: - res.status(405).json({ message: "Method not allowed" }); - break; + default: + res.status(405).json({ message: "Method not allowed" }); + break; + } } } diff --git a/pages/api/schedules/index.ts b/pages/api/schedules/index.ts index 3f5761e30d..bbdd1c8dbc 100644 --- a/pages/api/schedules/index.ts +++ b/pages/api/schedules/index.ts @@ -42,8 +42,10 @@ async function createOrlistAllSchedules( res: NextApiResponse ) { const { method } = req; + const userId = req.userId; + if (method === "GET") { - const data = await prisma.schedule.findMany(); + const data = await prisma.schedule.findMany({ where: { userId } }); const schedules = data.map((schedule) => schemaSchedulePublic.parse(schedule)); if (schedules) res.status(200).json({ schedules }); else @@ -55,8 +57,7 @@ async function createOrlistAllSchedules( } else if (method === "POST") { const safe = schemaScheduleBodyParams.safeParse(req.body); if (!safe.success) throw new Error("Invalid request body"); - - const data = await prisma.schedule.create({ data: safe.data }); + const data = await prisma.schedule.create({ data: { ...safe.data, userId } }); const schedule = schemaSchedulePublic.parse(data); if (schedule) res.status(201).json({ schedule, message: "Schedule created successfully" }); diff --git a/pages/api/selected-calendars/[id].ts b/pages/api/selected-calendars/[id].ts index 219d51dc4c..5c00b3895f 100644 --- a/pages/api/selected-calendars/[id].ts +++ b/pages/api/selected-calendars/[id].ts @@ -130,71 +130,85 @@ export async function selectedCalendarById( const safeBody = schemaSelectedCalendarBodyParams.safeParse(body); if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error); // This is how we set the userId and externalId in the query for managing compoundId. - const [userId, integration, externalId] = safeQuery.data.id.split("_"); - - switch (method) { - case "GET": - await prisma.selectedCalendar - .findUnique({ - where: { - userId_integration_externalId: { - userId: parseInt(userId), - integration: integration, - externalId: externalId, + const [paramUserId, integration, externalId] = safeQuery.data.id.split("_"); + const userId = req.userId; + if (userId !== parseInt(paramUserId)) res.status(401).json({ message: "Unauthorized" }); + else { + switch (method) { + case "GET": + await prisma.selectedCalendar + .findUnique({ + where: { + userId_integration_externalId: { + userId: userId, + integration: integration, + externalId: externalId, + }, }, - }, - }) - .then((selectedCalendar) => schemaSelectedCalendarPublic.parse(selectedCalendar)) - .then((selected_calendar) => res.status(200).json({ selected_calendar })) - .catch((error: Error) => - res.status(404).json({ message: `SelectedCalendar with id: ${safeQuery.data.id} not found`, error }) - ); - break; + }) + .then((selectedCalendar) => schemaSelectedCalendarPublic.parse(selectedCalendar)) + .then((selected_calendar) => res.status(200).json({ selected_calendar })) + .catch((error: Error) => + res.status(404).json({ + message: `SelectedCalendar with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "PATCH": - if (!safeBody.success) throw new Error("Invalid request body"); - await prisma.selectedCalendar - .update({ - where: { - userId_integration_externalId: { - userId: parseInt(userId), - integration: integration, - externalId: externalId, + case "PATCH": + if (!safeBody.success) { + throw new Error("Invalid request body"); + } + await prisma.selectedCalendar + .update({ + where: { + userId_integration_externalId: { + userId: userId, + integration: integration, + externalId: externalId, + }, }, - }, - data: safeBody.data, - }) - .then((selectedCalendar) => schemaSelectedCalendarPublic.parse(selectedCalendar)) - .then((selected_calendar) => res.status(200).json({ selected_calendar })) - .catch((error: Error) => - res.status(404).json({ message: `SelectedCalendar with id: ${safeQuery.data.id} not found`, error }) - ); - break; + data: safeBody.data, + }) + .then((selectedCalendar) => schemaSelectedCalendarPublic.parse(selectedCalendar)) + .then((selected_calendar) => res.status(200).json({ selected_calendar })) + .catch((error: Error) => + res.status(404).json({ + message: `SelectedCalendar with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "DELETE": - await prisma.selectedCalendar - .delete({ - where: { - userId_integration_externalId: { - userId: parseInt(userId), - integration: integration, - externalId: externalId, + case "DELETE": + await prisma.selectedCalendar + .delete({ + where: { + userId_integration_externalId: { + userId: userId, + integration: integration, + externalId: externalId, + }, }, - }, - }) - .then(() => - res - .status(200) - .json({ message: `SelectedCalendar with id: ${safeQuery.data.id} deleted successfully` }) - ) - .catch((error: Error) => - res.status(404).json({ message: `SelectedCalendar with id: ${safeQuery.data.id} not found`, error }) - ); - break; + }) + .then(() => + res.status(200).json({ + message: `SelectedCalendar with id: ${safeQuery.data.id} deleted successfully`, + }) + ) + .catch((error: Error) => + res.status(404).json({ + message: `SelectedCalendar with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - default: - res.status(405).json({ message: "Method not allowed" }); - break; + default: + res.status(405).json({ message: "Method not allowed" }); + break; + } } } diff --git a/pages/api/selected-calendars/index.ts b/pages/api/selected-calendars/index.ts index 15daead8a2..0ccde36943 100644 --- a/pages/api/selected-calendars/index.ts +++ b/pages/api/selected-calendars/index.ts @@ -7,7 +7,6 @@ import { SelectedCalendarResponse, SelectedCalendarsResponse } from "@lib/types" import { schemaSelectedCalendarBodyParams, schemaSelectedCalendarPublic, - withValidSelectedCalendar, } from "@lib/validations/selected-calendar"; /** @@ -46,8 +45,10 @@ async function createOrlistAllSelectedCalendars( res: NextApiResponse ) { const { method } = req; + const userId = req.userId; + if (method === "GET") { - const data = await prisma.selectedCalendar.findMany(); + const data = await prisma.selectedCalendar.findMany({ where: { userId } }); const selected_calendars = data.map((selected_calendar) => schemaSelectedCalendarPublic.parse(selected_calendar) ); @@ -61,8 +62,10 @@ async function createOrlistAllSelectedCalendars( } else if (method === "POST") { const safe = schemaSelectedCalendarBodyParams.safeParse(req.body); if (!safe.success) throw new Error("Invalid request body"); - - const data = await prisma.selectedCalendar.create({ data: safe.data }); + // Create new selectedCalendar connecting it to current userId + const data = await prisma.selectedCalendar.create({ + data: { ...safe.data, user: { connect: { id: userId } } }, + }); const selected_calendar = schemaSelectedCalendarPublic.parse(data); if (selected_calendar) @@ -76,6 +79,4 @@ async function createOrlistAllSelectedCalendars( } else res.status(405).json({ message: `Method ${method} not allowed` }); } -export default withMiddleware("HTTP_GET_OR_POST")( - withValidSelectedCalendar(createOrlistAllSelectedCalendars) -); +export default withMiddleware("HTTP_GET_OR_POST")(createOrlistAllSelectedCalendars); diff --git a/pages/api/teams/[id].ts b/pages/api/teams/[id].ts index 07da2e2870..f74937ecc5 100644 --- a/pages/api/teams/[id].ts +++ b/pages/api/teams/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { TeamResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaQueryIdParseInt, withValidQueryIdTransformParseInt, @@ -91,51 +90,65 @@ export async function teamById(req: NextApiRequest, res: NextApiResponse schemaTeamPublic.parse(data)) - .then((team) => res.status(200).json({ team })) - .catch((error: Error) => - res.status(404).json({ message: `Team with id: ${safeQuery.data.id} not found`, error }) - ); - break; + const userTeamIds = userWithMemberships.map((membership) => membership.teamId); + if (!userTeamIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { + switch (method) { + case "GET": + await prisma.team + .findUnique({ where: { id: safeQuery.data.id } }) + .then((data) => schemaTeamPublic.parse(data)) + .then((team) => res.status(200).json({ team })) + .catch((error: Error) => + res.status(404).json({ + message: `Team with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "PATCH": - if (!safeBody.success) throw new Error("Invalid request body"); - await prisma.team - .update({ - where: { id: safeQuery.data.id }, - data: safeBody.data, - }) - .then((team) => schemaTeamPublic.parse(team)) - .then((team) => res.status(200).json({ team })) - .catch((error: Error) => - res.status(404).json({ message: `Team with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "PATCH": + if (!safeBody.success) { + throw new Error("Invalid request body"); + } + await prisma.team + .update({ where: { id: safeQuery.data.id }, data: safeBody.data }) + .then((team) => schemaTeamPublic.parse(team)) + .then((team) => res.status(200).json({ team })) + .catch((error: Error) => + res.status(404).json({ + message: `Team with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - case "DELETE": - await prisma.team - .delete({ where: { id: safeQuery.data.id } }) - .then(() => - res.status(200).json({ message: `Team with id: ${safeQuery.data.id} deleted successfully` }) - ) - .catch((error: Error) => - res.status(404).json({ message: `Team with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "DELETE": + await prisma.team + .delete({ where: { id: safeQuery.data.id } }) + .then(() => + res.status(200).json({ + message: `Team with id: ${safeQuery.data.id} deleted successfully`, + }) + ) + .catch((error: Error) => + res.status(404).json({ + message: `Team with id: ${safeQuery.data.id} not found`, + error, + }) + ); + break; - default: - res.status(405).json({ message: "Method not allowed" }); - break; + default: + res.status(405).json({ message: "Method not allowed" }); + break; + } } } diff --git a/pages/api/teams/index.ts b/pages/api/teams/index.ts index d1c24bf8b8..045fc25461 100644 --- a/pages/api/teams/index.ts +++ b/pages/api/teams/index.ts @@ -4,7 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { TeamResponse, TeamsResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; +import { schemaMembershipPublic } from "@lib/validations/membership"; import { schemaTeamBodyParams, schemaTeamPublic, withValidTeam } from "@lib/validations/team"; /** @@ -40,7 +40,7 @@ import { schemaTeamBodyParams, schemaTeamPublic, withValidTeam } from "@lib/vali */ async function createOrlistAllTeams(req: NextApiRequest, res: NextApiResponse) { const { method } = req; - const userId = getCalcomUserId(res); + const userId = req.userId; if (method === "GET") { const userWithMemberships = await prisma.membership.findMany({ where: { userId: userId }, @@ -55,17 +55,23 @@ async function createOrlistAllTeams(req: NextApiRequest, res: NextApiResponse schemaMembershipPublic.parse(membership)); const data = schemaTeamPublic.parse(team); - - if (data) res.status(201).json({ team: data, message: "Team created successfully" }); + // We are also returning the new ownership relation as owner besides team. + if (data) + res.status(201).json({ + team: data, + owner: membership, + message: "Team created successfully, we also made you the owner of this team", + }); else (error: Error) => res.status(400).json({ diff --git a/pages/api/users/[id].ts b/pages/api/users/[id].ts index 5beaf442df..e1a11b3004 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 { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaQueryIdParseInt, withValidQueryIdTransformParseInt, @@ -91,8 +90,9 @@ export async function userById(req: NextApiRequest, res: NextApiResponse) { - const userId = getCalcomUserId(res); + const userId = req.userId; const data = await prisma.user.findMany({ where: { id: userId, diff --git a/tsconfig.json b/tsconfig.json index 5acb222ba6..4943d154a6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,23 +1,19 @@ { - "extends": "@calcom/tsconfig/base.json", - "exclude": ["node_modules", "templates"], + "extends": "@calcom/tsconfig/nextjs.json", "compilerOptions": { - "strictNullChecks": true, "baseUrl": ".", - - "target": "es5", - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "noEmit": true, - "incremental": true, - "module": "esnext", - "resolveJsonModule": true, - "jsx": "preserve", "paths": { "@api/*": ["pages/api/*"], "@lib/*": ["lib/*"], "@/*": ["*"] } }, - "include": ["./**/*.ts*"] + "include": [ + "next-env.d.ts", + "../../packages/types/*.d.ts", + "../../packages/types/next-auth.d.ts", + "**/*.ts", + "**/*.tsx" + ], + "exclude": ["node_modules", "templates"] }