From 29666493d6f616fea37cf1be30cc9de4d63fc199 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Tue, 19 Apr 2022 05:19:59 +0200 Subject: [PATCH 01/24] make event types return only userId data --- lib/validations/event-type.ts | 4 +- pages/api/event-types/[id].ts | 94 +++++++++++++++++++++------------- pages/api/event-types/index.ts | 11 +++- 3 files changed, 70 insertions(+), 39 deletions(-) diff --git a/lib/validations/event-type.ts b/lib/validations/event-type.ts index 113620157e..ab24a9b0d1 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({}); +// Omitting those two (locations/ metadata) because the validations where choking at array and JSON object. add them later if needed +export const schemaEventTypePublic = EventType.omit({ locations: true, metadata: true }); export const withValidEventType = withValidation({ schema: schemaEventTypeBodyParams, diff --git a/pages/api/event-types/[id].ts b/pages/api/event-types/[id].ts index 410cbbb5af..91ba0e380a 100644 --- a/pages/api/event-types/[id].ts +++ b/pages/api/event-types/[id].ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { EventTypeResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaEventTypeBodyParams, schemaEventTypePublic } from "@lib/validations/event-type"; import { schemaQueryIdParseInt, @@ -26,6 +27,8 @@ import { * - ApiKeyAuth: [] * tags: * - event-types + * externalDocs: + * url: https://docs.cal.com/event-types * responses: * 200: * description: OK @@ -55,6 +58,8 @@ import { * - ApiKeyAuth: [] * tags: * - event-types + * externalDocs: + * url: https://docs.cal.com/event-types * responses: * 201: * description: OK, eventType edited successfuly @@ -76,6 +81,8 @@ import { * - ApiKeyAuth: [] * tags: * - event-types + * externalDocs: + * url: https://docs.cal.com/event-types * responses: * 201: * description: OK, eventType removed successfuly @@ -90,44 +97,61 @@ export async function eventTypeById(req: NextApiRequest, res: NextApiResponse eventType.id); + if (userEventTypes.includes(safeQuery.data.id)) { + 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..cd883d719c 100644 --- a/pages/api/event-types/index.ts +++ b/pages/api/event-types/index.ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { EventTypeResponse, EventTypesResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaEventTypeBodyParams, schemaEventTypePublic } from "@lib/validations/event-type"; /** @@ -15,6 +16,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 +31,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 +47,10 @@ async function createOrlistAllEventTypes( res: NextApiResponse ) { const { method } = req; + const userId = await getCalcomUserId(res); + 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 +63,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" }); From 7734e86f6b62e6cc511aac5f290407879b91280f Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Tue, 19 Apr 2022 13:44:24 +0200 Subject: [PATCH 02/24] improve readme. fix event-types --- README.md | 109 ++++++++++++++++++---- lib/helpers/verifyApiKey.ts | 3 +- pages/api/availabilities/[id].ts | 6 ++ pages/api/availabilities/index.ts | 4 + pages/api/daily-event-references/index.ts | 4 +- 5 files changed, 106 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 81e06fa2ae..a79bb64f37 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,58 @@ # Cal.com Public API (Enterprise Only) -## This will be the new public enterprise-only API +This is the public REST api for cal.com. It exposes CRUD Endpoints of all our most important resources. It makes it easy for anyone to integrate with cal at the programming level. -This is the public REST api for cal.com +> The priority is the booking-related API routes so people can build their own booking flow, then event type management routes, then availability management routes etc -## NextJS + TypeScript +## Stack -It's a barebones **NextJS** + **TypeScript** project leveraging the nextJS API with a pages/api folder. +- NextJS +- TypeScript +- Prisma +- No tRPC (for now) We hook directly into prisma client, but probably should look into adding a new @calcom/trpc package that adds pagination and such stuff and can be shared between webapp and API. -- `api.cal.com/v1` -- `api.cal.com/api/v1` +## API Authentication (API Keys) + +The API requires a valid apiKey query param to be passed: +You can generate them at + +For example: +```sh +GET https://api.cal.com/v1/users?apiKey={INSERT_YOUR_CAL.COM_API_KEY_HERE} +``` + +API Keys optionally may have expiry dates, if they are expired they won't work. If you create an apiKey without a userId relation, it won't work either for now as it relies on it to establish the current authenticated user. + +In the future we might add support for header Beaer Auth if we need to or our customers require it. + +## Redirects + +Since this is an API only project, we don't want to have to type /api/ in all the routes, and so redirect all traffic to api, so a call to `api.cal.com/v1` will resolve to `api.cal.com/api/v1` + +Likewise, v1 is added as param query called version to final /api call so we don't duplicate endpoints in the future for versioning if needed. ## API Endpoint Validation -### Zod +We validate that only the supported methods are accepted at each endpoint, so in -The API uses `zod` library like our main web repo. It validates that either GET query parameters or POST body content's are valid and up to our spec. It gives appropiate errors when parsing result's with schemas. +- **/endpoint**: you can only [GET] (all) and [POST] (create new) +- **/endpoint/id**: you can read create and edit [GET, PATCH, DELETE] + +### Zod Validations + +The API uses `zod` library like our main web repo. It validates that either GET query parameters or POST body content's are valid and up to our spec. It gives errors when parsing result's with schemas and failing validation. + +We use it in several ways, but mainly, we first import the auto-generated schema from @calcom/prisma for each model, which lives in `lib/validations/` + +We have some shared validations which several resources require, like baseApiParams which parses apiKey in all requests, or querIdAsString or TransformParseInt which deal with the id's coming from req.query. + +- **[*]BaseBodyParams** that omits any values from the model that are too sensitive or we don't want to pick when creating a new resource like id, userId, etc.. (those are gotten from context or elswhere) + +- **[*]Public** that also omits any values that we don't want to expose when returning the model as a response, which we parse against before returning all resources. + +- **[*]BodyParams** which merges both `[*]BaseBodyParams.merge([*]RequiredParams);` + +- **withValid[*]** which is currently not being much used because is only useful in only post endpoints (we do post/get all in same file). This would validate the req.body of a POST call to API against our BaseBodyParams validation ### Next Validations @@ -29,14 +66,7 @@ We aim to provide a fully tested API for our peace of mind, this is accomplished ## Next.config.js -### Redirects - -Since this will only support an API, we redirect the requests to root to the /api folder. -We also added a redirect for future-proofing API versioning when we might need it, without having to resort to dirty hacks like a v1/v2 folders with lots of duplicated code, instead we redirect /api/v*/:rest to /api/:rest?version=* - -The priority is the booking-related API routes so people can build their own booking flow, then event type management routes, then availability management routes etc - -How to add a new model or endpoint +### How to add a new model or endpoint Basically there's three places of the codebase you need to think about for each feature. @@ -44,7 +74,7 @@ Basically there's three places of the codebase you need to think about for each - This is the most important one, and where your endpoint will live. You will leverage nextjs dynamic routes and expose one file for each endpoint you want to support ideally. -## How the codebase is organized. +## How the codebase is organized ## The example resource -model- and it's endpoints @@ -77,3 +107,48 @@ tests/endpoint/resource.new.test.ts - Create new resource ## `/lib/validations/yourEndpoint.ts` - This is where our model validations, live, we try to make a 1:1 for db models, and also extract out any re-usable code into the /lib/validations/shared/ sub-folder. + +## Endpoints matrix + +| resource | get [id] | get all | create | edit | delete | +|--------------------------|----------|----------|---------|-------|--------| +| attendees | ✅ | ✅ | ✅ | ✅ | ✅ | +| availabilities | ✅ | ✅ | ✅ | ✅ | ✅ | +| booking-references | ✅ | ✅ | ✅ | ✅ | ✅ | +| daily-event-references | ✅ | ✅ | ✅ | ✅ | ✅ | +| destination-calendars | ✅ | ✅ | ✅ | ✅ | ✅ | +| event-type-custom-inputs | ✅ | ✅ | ✅ | ✅ | ✅ | +| event-types | ✅ | ✅ | ✅ | ✅ | ✅ | +| memberships | ✅ | ✅ | ✅ | ✅ | ✅ | +| payments | ✅ | ✅ | ❌ | ❌ | ❌ | +| reminder-mails | ✅ | ✅ | ✅ | ✅ | ✅ | +| schedules | ✅ | ✅ | ✅ | ✅ | ✅ | +| selected-calendars | ✅ | ✅ | ✅ | ✅ | ✅ | +| teams | ✅ | ✅ | ✅ | ✅ | ✅ | +| users | ✅ | 👤[1] | ✅ | ✅ | ✅ | + +## Models from database that are not exposed + +mostly because they're deemed too sensitive can be revisited if needed. + +- [] Api Keys +- [] Credentials + +## Documentation (OpenAPI) + +You will see that each endpoint has a comment at the top with the annotation `@swagger` with the documentation of the endpoint, **please update it if you change the code!** This is what auto-generates the OpenAPI spec by collecting the YAML in each endpoint and parsing it in /docs alongside the json-schema (auto-generated from prisma package, not added to code but manually for now, need to fix later) + +### @calcom/apps/swagger + +The documentation of the API lives inside the code, and it's auto-generated, the only endpoints that return without a valid apiKey are the homepage, with a JSON message redirecting you to the docs. and the /docs endpoint, which returns the OpenAPI 3.0 JSON Spec. Which SwaggerUi then consumes and generates the docs on. + +## Deployment + +`scripts/vercel-deploy.sh` +The API is deployed to vercel.com, it uses a similar deployment script to website or webapp, and requires transpilation of several shared packages that are part of our turborepo ["app-store", "prisma", "lib", "ee"] +in order to build and deploy properly. + +## Envirorment variables + +DATABASE_URL= +API_KEY_PREFIX=cal_# This can be changed per envirorment so cal_test_ for staging for example. diff --git a/lib/helpers/verifyApiKey.ts b/lib/helpers/verifyApiKey.ts index 008f3dc4f4..0ee197456c 100644 --- a/lib/helpers/verifyApiKey.ts +++ b/lib/helpers/verifyApiKey.ts @@ -26,7 +26,8 @@ export const verifyApiKey: NextMiddleware = async (req, res, next) => { // 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); + if (apiKey.userId) res.setHeader("X-Calcom-User-ID", apiKey.userId); + // Pass the request to the next middleware. await next(); } diff --git a/pages/api/availabilities/[id].ts b/pages/api/availabilities/[id].ts index feeef587c0..90d0f72fc1 100644 --- a/pages/api/availabilities/[id].ts +++ b/pages/api/availabilities/[id].ts @@ -27,6 +27,8 @@ import { * - ApiKeyAuth: [] * tags: * - availabilities + * externalDocs: + * url: https://docs.cal.com/availability * responses: * 200: * description: OK @@ -56,6 +58,8 @@ import { * - ApiKeyAuth: [] * tags: * - availabilities + * externalDocs: + * url: https://docs.cal.com/availability * responses: * 201: * description: OK, availability edited successfuly @@ -77,6 +81,8 @@ import { * - ApiKeyAuth: [] * tags: * - availabilities + * externalDocs: + * url: https://docs.cal.com/availability * responses: * 201: * description: OK, availability removed successfuly diff --git a/pages/api/availabilities/index.ts b/pages/api/availabilities/index.ts index 558b948d30..bcd904ce95 100644 --- a/pages/api/availabilities/index.ts +++ b/pages/api/availabilities/index.ts @@ -16,6 +16,8 @@ import { schemaAvailabilityBodyParams, schemaAvailabilityPublic } from "@lib/val * - ApiKeyAuth: [] * tags: * - availabilities + * externalDocs: + * url: https://docs.cal.com/availability * responses: * 200: * description: OK @@ -29,6 +31,8 @@ import { schemaAvailabilityBodyParams, schemaAvailabilityPublic } from "@lib/val * - ApiKeyAuth: [] * tags: * - availabilities + * externalDocs: + * url: https://docs.cal.com/availability * responses: * 201: * description: OK, availability created diff --git a/pages/api/daily-event-references/index.ts b/pages/api/daily-event-references/index.ts index aa60482bb1..e3a90d6f03 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 From 12dbb0ad032f2ca4e68b874227d169ae359c00b8 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Wed, 20 Apr 2022 16:06:37 +0200 Subject: [PATCH 03/24] feat: final securing of all endpoints, update readme --- README.md | 14 +++ tests/api-keys/[id]/api-key.id.delete.test.ts | 86 --------------- tests/api-keys/[id]/api-key.id.edit.test.ts | 103 ------------------ tests/api-keys/[id]/api-key.id.index.test.ts | 83 -------------- tests/api-keys/api-key.index.test.ts | 39 ------- tests/api-keys/api-key.new.test.ts | 77 ------------- 6 files changed, 14 insertions(+), 388 deletions(-) delete mode 100644 tests/api-keys/[id]/api-key.id.delete.test.ts delete mode 100644 tests/api-keys/[id]/api-key.id.edit.test.ts delete mode 100644 tests/api-keys/[id]/api-key.id.index.test.ts delete mode 100644 tests/api-keys/api-key.index.test.ts delete mode 100644 tests/api-keys/api-key.new.test.ts diff --git a/README.md b/README.md index a79bb64f37..5aed701aff 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,17 @@ This is the public REST api for cal.com. It exposes CRUD Endpoints of all our mo - Prisma - No tRPC (for now) We hook directly into prisma client, but probably should look into adding a new @calcom/trpc package that adds pagination and such stuff and can be shared between webapp and API. + +## How to run it + +First clone the main repo with --recursive-submodules flag. This will clone our monorepo, and all the private git submodules within it. +`` +Be sure to be authenticated in gh-cli or via PAT in your shell, as this will clone private repos that requires this (website, api) +`` + +`cp .env.example .env` + +`yarn workspace @calcom/api dev ## API Authentication (API Keys) The API requires a valid apiKey query param to be passed: @@ -133,6 +144,9 @@ mostly because they're deemed too sensitive can be revisited if needed. - [] Api Keys - [] Credentials +- [] Webhooks +- [] ResetPasswordRequest +- [] VerificationToken ## Documentation (OpenAPI) diff --git a/tests/api-keys/[id]/api-key.id.delete.test.ts b/tests/api-keys/[id]/api-key.id.delete.test.ts deleted file mode 100644 index d2abfecb7a..0000000000 --- a/tests/api-keys/[id]/api-key.id.delete.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import handleDeleteApiKey from "@api/api-keys/[id]/delete"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -describe("DELETE /api/api-keys/[id]/delete with valid id as string returns an apiKey", () => { - it("returns a message with the specified apiKeys", async () => { - const apiKey = await prisma.apiKey.findFirst(); - const { req, res } = createMocks({ - method: "DELETE", - query: { - id: apiKey?.id, - }, - }); - // const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.id} }); - await handleDeleteApiKey(req, res); - expect(res._getStatusCode()).toBe(204); - expect(JSON.parse(res._getData())).toEqual({ - message: `api-key with id: ${apiKey?.id} deleted successfully`, - }); - }); -}); - -// This can never happen under our normal nextjs setup where query is always a string | string[]. -// But seemed a good example for testing an error validation -describe("DELETE /api/api-keys/[id]/delete errors if query id is number, requires a string", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "DELETE", - query: { - id: 1, // passing query as a number, which should fail as nextjs will try to parse it as a string - }, - }); - await handleDeleteApiKey(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "invalid_type", - expected: "string", - received: "number", - path: ["id"], - message: "Expected string, received number", - }, - ]); - }); -}); - -describe("DELETE /api/api-keys/[id]/delete an id not present in db like 0, throws 404 not found", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "DELETE", - query: { - id: "0", // There's no apiKey with id 0 - }, - }); - await handleDeleteApiKey(req, res); - - expect(res._getStatusCode()).toBe(404); - expect(JSON.parse(res._getData())).toStrictEqual({ - error: { - clientVersion: "3.10.0", - code: "P2025", - meta: { - cause: "Record to delete does not exist.", - }, - }, - message: "Resource with id:0 was not found", - }); - }); -}); - -describe("POST /api/api-keys/[id]/delete fails, only DELETE allowed", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "1", - }, - }); - await handleDeleteApiKey(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only DELETE Method allowed" }); - }); -}); diff --git a/tests/api-keys/[id]/api-key.id.edit.test.ts b/tests/api-keys/[id]/api-key.id.edit.test.ts deleted file mode 100644 index 1007181179..0000000000 --- a/tests/api-keys/[id]/api-key.id.edit.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import handleapiKeyEdit from "@api/api-keys/[id]/edit"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -import { stringifyISODate } from "@lib/utils/stringifyISODate"; - -describe("PATCH /api/api-keys/[id]/edit with valid id and body with note", () => { - it("returns a 200 and the updated apiKey note", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "cl16zg6860000wwylnsgva00b", - }, - body: { - note: "Updated note", - }, - }); - const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.id } }); - await handleapiKeyEdit(req, res); - - expect(res._getStatusCode()).toBe(200); - expect(JSON.parse(res._getData())).toEqual({ - data: { - ...apiKey, - createdAt: stringifyISODate(apiKey?.createdAt), - expiresAt: stringifyISODate(apiKey?.expiresAt), - }, - }); - }); -}); - -describe("PATCH /api/api-keys/[id]/edit with invalid id returns 404", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "cl16zg6860000wwylnsgva00a", - }, - body: { - note: "Updated note", - }, - }); - const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.id } }); - await handleapiKeyEdit(req, res); - - expect(res._getStatusCode()).toBe(404); - if (apiKey) apiKey.note = "Updated note"; - expect(JSON.parse(res._getData())).toStrictEqual({ - error: { - clientVersion: "3.10.0", - code: "P2025", - meta: { - cause: "Record to update not found.", - }, - }, - message: "apiKey with ID cl16zg6860000wwylnsgva00a not found and wasn't updated", - }); - }); -}); - -describe("PATCH /api/api-keys/[id]/edit with valid id and no body returns 200 with an apiKey with no note and default expireAt", () => { - it("returns a message with the specified apiKeys", async () => { - const apiKey = await prisma.apiKey.create({ data: {} }); - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: apiKey?.id, - }, - }); - await handleapiKeyEdit(req, res); - - expect(apiKey?.note).toBeNull(); - expect(res._getStatusCode()).toBe(200); - expect(JSON.parse(res._getData())).toEqual({ - data: { - ...apiKey, - createdAt: stringifyISODate(apiKey?.createdAt), - expiresAt: stringifyISODate(apiKey?.expiresAt), - }, - }); - }); -}); - -describe("POST /api/api-keys/[id]/edit fails, only PATCH allowed", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "cl16zg6860000wwylnsgva00b", - }, - body: { - note: "Updated note", - }, - }); - await handleapiKeyEdit(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ - message: "Only PATCH Method allowed for updating API keys", - }); - }); -}); diff --git a/tests/api-keys/[id]/api-key.id.index.test.ts b/tests/api-keys/[id]/api-key.id.index.test.ts deleted file mode 100644 index 8d3c2655af..0000000000 --- a/tests/api-keys/[id]/api-key.id.index.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import handleApiKey from "@api/api-keys/[id]"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -import { stringifyISODate } from "@lib/utils/stringifyISODate"; - -describe("GET /api/api-keys/[id] with valid id as string returns an apiKey", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: "cl16zg6860000wwylnsgva00b", - }, - }); - const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.id } }); - await handleApiKey(req, res); - - expect(res._getStatusCode()).toBe(200); - expect(JSON.parse(res._getData())).toEqual({ - data: { - ...apiKey, - createdAt: stringifyISODate(apiKey?.createdAt), - expiresAt: stringifyISODate(apiKey?.expiresAt), - }, - }); - }); -}); - -// This can never happen under our normal nextjs setup where query is always a string | string[]. -// But seemed a good example for testing an error validation -describe("GET /api/api-keys/[id] errors if query id is number, requires a string", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: 1, // passing query as a number, which should fail as nextjs will try to parse it as a string - }, - }); - await handleApiKey(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "invalid_type", - expected: "string", - received: "number", - path: ["id"], - message: "Expected string, received number", - }, - ]); - }); -}); - -describe("GET /api/api-keys/[id] an id not present in db like 0, throws 404 not found", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: "0", // There's no apiKey with id 0 - }, - }); - await handleApiKey(req, res); - - expect(res._getStatusCode()).toBe(404); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "API key was not found" }); - }); -}); - -describe("POST /api/api-keys/[id] fails, only GET allowed", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "1", - }, - }); - await handleApiKey(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" }); - }); -}); diff --git a/tests/api-keys/api-key.index.test.ts b/tests/api-keys/api-key.index.test.ts deleted file mode 100644 index 957b749b88..0000000000 --- a/tests/api-keys/api-key.index.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import handleApiKeys from "@api/api-keys"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -import { stringifyISODate } from "@lib/utils/stringifyISODate"; - -describe("GET /api/api-keys without any params", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "GET", - query: {}, - }); - let apiKeys = await prisma.apiKey.findMany(); - await handleApiKeys(req, res); - - expect(res._getStatusCode()).toBe(200); - apiKeys = apiKeys.map( - (apiKey) => - (apiKey = { - ...apiKey, - createdAt: stringifyISODate(apiKey?.createdAt), - expiresAt: stringifyISODate(apiKey?.expiresAt), - }) - ); - expect(JSON.parse(res._getData())).toStrictEqual(JSON.parse(JSON.stringify({ data: { ...apiKeys } }))); - }); -}); - -describe("POST /api/api-keys/ fails, only GET allowed", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - }); - await handleApiKeys(req, res); - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" }); - }); -}); diff --git a/tests/api-keys/api-key.new.test.ts b/tests/api-keys/api-key.new.test.ts deleted file mode 100644 index 339b4c146b..0000000000 --- a/tests/api-keys/api-key.new.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import handleNewApiKey from "@api/api-keys/new"; -import { createMocks } from "node-mocks-http"; - -describe("POST /api/api-keys/new with a note", () => { - it("returns a 201, and the created api key", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - body: { - note: "Updated note", - }, - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(201); - expect(JSON.parse(res._getData()).data.note).toStrictEqual("Updated note"); - }); -}); - -describe("POST /api/api-keys/new with a slug param", () => { - it("returns error 400, and the details about invalid slug body param", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - body: { - note: "Updated note", - slug: "slug", - }, - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "unrecognized_keys", - keys: ["slug"], - message: "Unrecognized key(s) in object: 'slug'", - path: [], - }, - ]); - }); -}); - -describe("GET /api/api-keys/new fails, only POST allowed", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "GET", // This POST method is not allowed - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ error: "Only POST Method allowed" }); - }); -}); - -// FIXME: test 405 when prisma fails look for how to test prisma errors -describe("GET /api/api-keys/new fails, only POST allowed", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - body: { - nonExistentParam: true, - // note: '123', - // slug: 12, - }, - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "unrecognized_keys", - keys: ["nonExistentParam"], - message: "Unrecognized key(s) in object: 'nonExistentParam'", - path: [], - }, - ]); - }); -}); From e138df47bad1ad57b12d851c7d1dd22138739195 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Wed, 20 Apr 2022 20:25:26 +0200 Subject: [PATCH 04/24] remove duplicated error check in event-types id --- pages/api/event-types/[id].ts | 1 - 1 file changed, 1 deletion(-) diff --git a/pages/api/event-types/[id].ts b/pages/api/event-types/[id].ts index 91ba0e380a..c19822d65b 100644 --- a/pages/api/event-types/[id].ts +++ b/pages/api/event-types/[id].ts @@ -97,7 +97,6 @@ export async function eventTypeById(req: NextApiRequest, res: NextApiResponse eventType.id); From ec903b21c6b6bd3e3da5a4fe8b4f0de8f3ed8978 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Wed, 20 Apr 2022 23:42:49 +0200 Subject: [PATCH 05/24] feat: teams return only userId related data, on POST create ownership membership for userId --- README.md | 13 ++++++ lib/types.ts | 1 + pages/api/teams/[id].ts | 87 +++++++++++++++++++++++----------------- pages/api/teams/index.ts | 20 ++++++--- 4 files changed, 78 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 5aed701aff..aa06e86e58 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,17 @@ tests/endpoint/resource.new.test.ts - Create new resource | teams | ✅ | ✅ | ✅ | ✅ | ✅ | | users | ✅ | 👤[1] | ✅ | ✅ | ✅ | +## Models missing userId relation. + +- daily-event-references +- destination-calendars +- event-types-custom-input +- memberships +- reminder-mails +- schedules +- selected-calendars +- teams + ## Models from database that are not exposed mostly because they're deemed too sensitive can be revisited if needed. @@ -166,3 +177,5 @@ in order to build and deploy properly. DATABASE_URL= API_KEY_PREFIX=cal_# This can be changed per envirorment so cal_test_ for staging for example. + +If you're self-hosting under our commercial license, you can use any prefix you want for api keys. either leave the default cal_ (not providing any envirorment variable) or modify it 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/pages/api/teams/[id].ts b/pages/api/teams/[id].ts index 07da2e2870..de14a27c3d 100644 --- a/pages/api/teams/[id].ts +++ b/pages/api/teams/[id].ts @@ -97,46 +97,59 @@ 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)) { + 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; + } + } else res.status(401).json({ message: "Unauthorized" }); } export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(teamById)); diff --git a/pages/api/teams/index.ts b/pages/api/teams/index.ts index d1c24bf8b8..3fcd7d7d05 100644 --- a/pages/api/teams/index.ts +++ b/pages/api/teams/index.ts @@ -5,6 +5,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"; /** @@ -59,13 +60,20 @@ async function createOrlistAllTeams(req: NextApiRequest, res: NextApiResponse schemaMembershipPublic.parse(membership)); + // We're also creating the relation membership of team ownership in this call. 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({ From 910f222d626bd44f2f009e96144b2d5b038cb80c Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Wed, 20 Apr 2022 23:43:40 +0200 Subject: [PATCH 06/24] fix: remove teams from endpoints that need hardening --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index aa06e86e58..42c02cfd23 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,6 @@ tests/endpoint/resource.new.test.ts - Create new resource - reminder-mails - schedules - selected-calendars -- teams ## Models from database that are not exposed From 6749840077542a1e998c56d9ad96a5eca03e06e5 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 21 Apr 2022 00:00:02 +0200 Subject: [PATCH 07/24] fix: improve comments on teams --- pages/api/teams/index.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pages/api/teams/index.ts b/pages/api/teams/index.ts index 3fcd7d7d05..a480bff97a 100644 --- a/pages/api/teams/index.ts +++ b/pages/api/teams/index.ts @@ -56,16 +56,15 @@ async function createOrlistAllTeams(req: NextApiRequest, res: NextApiResponse schemaMembershipPublic.parse(membership)); - // We're also creating the relation membership of team ownership in this call. const data = schemaTeamPublic.parse(team); // We are also returning the new ownership relation as owner besides team. if (data) From 80c2c4bdae4a840fa6e731ce68f88646fdb933f4 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 21 Apr 2022 00:31:42 +0200 Subject: [PATCH 08/24] feat: selected calendars hardened --- README.md | 1 - pages/api/selected-calendars/[id].ts | 134 ++++++++++++++------------ pages/api/selected-calendars/index.ts | 16 +-- 3 files changed, 83 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index 42c02cfd23..c3faa6a283 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,6 @@ tests/endpoint/resource.new.test.ts - Create new resource - memberships - reminder-mails - schedules -- selected-calendars ## Models from database that are not exposed diff --git a/pages/api/selected-calendars/[id].ts b/pages/api/selected-calendars/[id].ts index 219d51dc4c..69cd9c059e 100644 --- a/pages/api/selected-calendars/[id].ts +++ b/pages/api/selected-calendars/[id].ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { SelectedCalendarResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaSelectedCalendarBodyParams, schemaSelectedCalendarPublic, @@ -130,72 +131,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 = getCalcomUserId(res); + if (userId === parseInt(paramUserId)) { + 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; + } + } else res.status(401).json({ message: "Unauthorized" }); } export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdString(selectedCalendarById)); diff --git a/pages/api/selected-calendars/index.ts b/pages/api/selected-calendars/index.ts index 15daead8a2..cb12a5dac7 100644 --- a/pages/api/selected-calendars/index.ts +++ b/pages/api/selected-calendars/index.ts @@ -4,10 +4,10 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { SelectedCalendarResponse, SelectedCalendarsResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaSelectedCalendarBodyParams, schemaSelectedCalendarPublic, - withValidSelectedCalendar, } from "@lib/validations/selected-calendar"; /** @@ -46,8 +46,10 @@ async function createOrlistAllSelectedCalendars( res: NextApiResponse ) { const { method } = req; + const userId = getCalcomUserId(res); + 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 +63,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 +80,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); From cabe4ae9c60f05145d1b24a5fa6a72a26a30163c Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 21 Apr 2022 00:48:54 +0200 Subject: [PATCH 09/24] feat: schedules hardend --- README.md | 19 ++++---- pages/api/schedules/[id].ts | 91 +++++++++++++++++++++--------------- pages/api/schedules/index.ts | 8 ++-- 3 files changed, 68 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index c3faa6a283..3731387b94 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,9 @@ This is the public REST api for cal.com. It exposes CRUD Endpoints of all our mo - NextJS - TypeScript - Prisma -- No tRPC (for now) We hook directly into prisma client, but probably should look into adding a new @calcom/trpc package that adds pagination and such stuff and can be shared between webapp and API. +- No tRPC ** + +** (for now) We hook directly into prisma client, but probably should look into adding a new @calcom/trpc package that adds pagination and such stuff and can be shared between webapp and API. ## How to run it @@ -138,24 +140,23 @@ tests/endpoint/resource.new.test.ts - Create new resource | teams | ✅ | ✅ | ✅ | ✅ | ✅ | | users | ✅ | 👤[1] | ✅ | ✅ | ✅ | -## Models missing userId relation. +## Models missing userId relation - daily-event-references - destination-calendars - event-types-custom-input - memberships - reminder-mails -- schedules ## Models from database that are not exposed -mostly because they're deemed too sensitive can be revisited if needed. +mostly because they're deemed too sensitive can be revisited if needed. most are expected to be used via cal's webapp. -- [] Api Keys -- [] Credentials -- [] Webhooks -- [] ResetPasswordRequest -- [] VerificationToken +- [ ] Api Keys +- [ ] Credentials +- [ ] Webhooks +- [ ] ResetPasswordRequest +- [ ] VerificationToken ## Documentation (OpenAPI) diff --git a/pages/api/schedules/[id].ts b/pages/api/schedules/[id].ts index eb87d13949..1b46e62269 100644 --- a/pages/api/schedules/[id].ts +++ b/pages/api/schedules/[id].ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { ScheduleResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaScheduleBodyParams, schemaSchedulePublic } from "@lib/validations/schedule"; import { schemaQueryIdParseInt, @@ -90,47 +91,61 @@ export async function scheduleById(req: NextApiRequest, res: NextApiResponse schedule.id); + if (userScheduleIds.includes(safeQuery.data.id)) { + 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; + } + } else res.status(401).json({ message: "Unauthorized" }); } export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(scheduleById)); diff --git a/pages/api/schedules/index.ts b/pages/api/schedules/index.ts index 3f5761e30d..cb4eeaeb9d 100644 --- a/pages/api/schedules/index.ts +++ b/pages/api/schedules/index.ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { ScheduleResponse, SchedulesResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaScheduleBodyParams, schemaSchedulePublic, withValidSchedule } from "@lib/validations/schedule"; /** @@ -42,8 +43,10 @@ async function createOrlistAllSchedules( res: NextApiResponse ) { const { method } = req; + const userId = getCalcomUserId(res); + 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 +58,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" }); From 9c5624c748f82e5e4a4d67e64a7732ebd647b3bc Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 21 Apr 2022 00:50:34 +0200 Subject: [PATCH 10/24] fix: delete reminder mails endpoints for now as no userId, consult if needed --- pages/api/reminder-mails/[id].ts | 136 ------------------------------ pages/api/reminder-mails/index.ts | 76 ----------------- 2 files changed, 212 deletions(-) delete mode 100644 pages/api/reminder-mails/[id].ts delete mode 100644 pages/api/reminder-mails/index.ts 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)); From b0c0e9fb4cb74bf37bd5c748a621df2339ab05db Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 21 Apr 2022 00:55:22 +0200 Subject: [PATCH 11/24] feat: memberships hardened mode --- pages/api/memberships/[id].ts | 113 +++++++++++++++++++++------------ pages/api/memberships/index.ts | 6 +- 2 files changed, 78 insertions(+), 41 deletions(-) diff --git a/pages/api/memberships/[id].ts b/pages/api/memberships/[id].ts index 2fbb14bcdb..df62f89107 100644 --- a/pages/api/memberships/[id].ts +++ b/pages/api/memberships/[id].ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { MembershipResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaMembershipBodyParams, schemaMembershipPublic } from "@lib/validations/membership"; import { schemaQueryIdAsString, withValidQueryIdString } from "@lib/validations/shared/queryIdString"; @@ -106,48 +107,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; + } + } else res.status(401).json({ message: "Unauthorized" }); } export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdString(membershipById)); diff --git a/pages/api/memberships/index.ts b/pages/api/memberships/index.ts index 85c2ddced1..a7a109da2d 100644 --- a/pages/api/memberships/index.ts +++ b/pages/api/memberships/index.ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { MembershipResponse, MembershipsResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaMembershipBodyParams, schemaMembershipPublic } from "@lib/validations/membership"; /** @@ -42,8 +43,9 @@ async function createOrlistAllMemberships( res: NextApiResponse ) { const { method } = req; + const userId = getCalcomUserId(res); 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 +58,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" }); From 18c1a2f026bc1106e74c0e41ba108c956df9e6c0 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 21 Apr 2022 00:55:41 +0200 Subject: [PATCH 12/24] remove unnecessary await on all getCalcomUserId() calls --- pages/api/attendees/index.ts | 2 +- pages/api/availabilities/[id].ts | 2 +- pages/api/availabilities/index.ts | 2 +- pages/api/booking-references/[id].ts | 2 +- pages/api/booking-references/index.ts | 4 ++-- pages/api/bookings/[id].ts | 2 +- pages/api/bookings/index.ts | 2 +- pages/api/event-types/[id].ts | 2 +- pages/api/event-types/index.ts | 2 +- pages/api/payments/[id].ts | 2 +- pages/api/payments/index.ts | 2 +- 11 files changed, 12 insertions(+), 12 deletions(-) diff --git a/pages/api/attendees/index.ts b/pages/api/attendees/index.ts index ed0707d636..d96fe3bca4 100644 --- a/pages/api/attendees/index.ts +++ b/pages/api/attendees/index.ts @@ -68,7 +68,7 @@ async function createOrlistAllAttendees( throw new Error("Invalid request body", safe.error); } const bookingId = safe.data.bookingId; - const userId = await getCalcomUserId(res); + const userId = getCalcomUserId(res); const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, include: { bookings: true }, diff --git a/pages/api/availabilities/[id].ts b/pages/api/availabilities/[id].ts index 90d0f72fc1..bdb1215f74 100644 --- a/pages/api/availabilities/[id].ts +++ b/pages/api/availabilities/[id].ts @@ -97,7 +97,7 @@ 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 = getCalcomUserId(res); const data = await prisma.availability.findMany({ where: { userId } }); const availabiltiesIds = data.map((availability) => availability.id); if (availabiltiesIds.includes(safeQuery.data.id)) { diff --git a/pages/api/availabilities/index.ts b/pages/api/availabilities/index.ts index bcd904ce95..63ae75db49 100644 --- a/pages/api/availabilities/index.ts +++ b/pages/api/availabilities/index.ts @@ -47,7 +47,7 @@ async function createOrlistAllAvailabilities( res: NextApiResponse ) { const { method } = req; - const userId = await getCalcomUserId(res); + const userId = getCalcomUserId(res); 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..9a1b40089b 100644 --- a/pages/api/booking-references/[id].ts +++ b/pages/api/booking-references/[id].ts @@ -98,7 +98,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 = getCalcomUserId(res); 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..9ceedeed30 100644 --- a/pages/api/booking-references/index.ts +++ b/pages/api/booking-references/index.ts @@ -46,7 +46,7 @@ async function createOrlistAllBookingReferences( res: NextApiResponse ) { const { method } = req; - const userId = await getCalcomUserId(res); + const userId = getCalcomUserId(res); const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, include: { bookings: true }, @@ -72,7 +72,7 @@ async function createOrlistAllBookingReferences( } // const booking_reference = schemaBookingReferencePublic.parse(data); - const userId = await getCalcomUserId(res); + const userId = getCalcomUserId(res); const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, include: { bookings: true }, diff --git a/pages/api/bookings/[id].ts b/pages/api/bookings/[id].ts index e3e56b9a36..af6a379158 100644 --- a/pages/api/bookings/[id].ts +++ b/pages/api/bookings/[id].ts @@ -91,7 +91,7 @@ export async function bookingById(req: NextApiRequest, res: NextApiResponse ) { const { method } = req; - const userId = await getCalcomUserId(res); + const userId = getCalcomUserId(res); if (method === "GET") { const data = await prisma.booking.findMany({ where: { userId } }); diff --git a/pages/api/event-types/[id].ts b/pages/api/event-types/[id].ts index c19822d65b..dc7535cd5a 100644 --- a/pages/api/event-types/[id].ts +++ b/pages/api/event-types/[id].ts @@ -97,7 +97,7 @@ export async function eventTypeById(req: NextApiRequest, res: NextApiResponse eventType.id); if (userEventTypes.includes(safeQuery.data.id)) { diff --git a/pages/api/event-types/index.ts b/pages/api/event-types/index.ts index cd883d719c..fc6a2a35f7 100644 --- a/pages/api/event-types/index.ts +++ b/pages/api/event-types/index.ts @@ -47,7 +47,7 @@ async function createOrlistAllEventTypes( res: NextApiResponse ) { const { method } = req; - const userId = await getCalcomUserId(res); + const userId = getCalcomUserId(res); if (method === "GET") { const data = await prisma.eventType.findMany({ where: { userId } }); diff --git a/pages/api/payments/[id].ts b/pages/api/payments/[id].ts index f196b4cac0..295803ca76 100644 --- a/pages/api/payments/[id].ts +++ b/pages/api/payments/[id].ts @@ -38,7 +38,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 = getCalcomUserId(res); if (safeQuery.success && method === "GET") { const userWithBookings = await prisma.user.findUnique({ diff --git a/pages/api/payments/index.ts b/pages/api/payments/index.ts index 20028df180..bb2c132c0c 100644 --- a/pages/api/payments/index.ts +++ b/pages/api/payments/index.ts @@ -25,7 +25,7 @@ import { schemaPaymentPublic } from "@lib/validations/payment"; * description: No payments were found */ async function allPayments(_: NextApiRequest, res: NextApiResponse) { - const userId = await getCalcomUserId(res); + const userId = getCalcomUserId(res); const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, From d8bfff95254494dbe3138c82a8dab2e20b366101 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 21 Apr 2022 01:08:45 +0200 Subject: [PATCH 13/24] feat: event type custom input endpoitns ready --- README.md | 8 +- pages/api/event-type-custom-inputs/[id].ts | 99 +++++++++++++-------- pages/api/event-type-custom-inputs/index.ts | 37 ++++++-- 3 files changed, 93 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 3731387b94..480973762b 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,6 @@ tests/endpoint/resource.new.test.ts - Create new resource | event-types | ✅ | ✅ | ✅ | ✅ | ✅ | | memberships | ✅ | ✅ | ✅ | ✅ | ✅ | | payments | ✅ | ✅ | ❌ | ❌ | ❌ | -| reminder-mails | ✅ | ✅ | ✅ | ✅ | ✅ | | schedules | ✅ | ✅ | ✅ | ✅ | ✅ | | selected-calendars | ✅ | ✅ | ✅ | ✅ | ✅ | | teams | ✅ | ✅ | ✅ | ✅ | ✅ | @@ -144,9 +143,7 @@ tests/endpoint/resource.new.test.ts - Create new resource - daily-event-references - destination-calendars -- event-types-custom-input -- memberships -- reminder-mails + ## Models from database that are not exposed @@ -157,7 +154,8 @@ mostly because they're deemed too sensitive can be revisited if needed. most are - [ ] Webhooks - [ ] ResetPasswordRequest - [ ] VerificationToken - +- [ ] ReminderMail +- [ ] ## Documentation (OpenAPI) You will see that each endpoint has a comment at the top with the annotation `@swagger` with the documentation of the endpoint, **please update it if you change the code!** This is what auto-generates the OpenAPI spec by collecting the YAML in each endpoint and parsing it in /docs alongside the json-schema (auto-generated from prisma package, not added to code but manually for now, need to fix later) diff --git a/pages/api/event-type-custom-inputs/[id].ts b/pages/api/event-type-custom-inputs/[id].ts index d9dd21d112..5a00436361 100644 --- a/pages/api/event-type-custom-inputs/[id].ts +++ b/pages/api/event-type-custom-inputs/[id].ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { EventTypeCustomInputResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaEventTypeCustomInputBodyParams, schemaEventTypeCustomInputPublic, @@ -93,47 +94,69 @@ 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)) { + 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; + } + } else res.status(401).json({ message: "Unauthorized" }); } export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(eventTypeById)); diff --git a/pages/api/event-type-custom-inputs/index.ts b/pages/api/event-type-custom-inputs/index.ts index 806d3ca91e..e6c0c852bf 100644 --- a/pages/api/event-type-custom-inputs/index.ts +++ b/pages/api/event-type-custom-inputs/index.ts @@ -45,8 +45,17 @@ async function createOrlistAllEventTypeCustomInputs( res: NextApiResponse ) { const { method } = req; + const userId = getCalcomUserId(res); + const data = await prisma.eventType.findMany({ where: { userId } }); + const userEventTypes = data.map((eventType) => eventType.id); + // const userEventTypeCustomInputs = await prisma.eventTypeCustomInput.findMany({ + // where: { eventType: userEventTypes }, + // }); + // const userEventTypeCustomInputIds = userEventTypeCustomInputs.map( + // (eventTypeCustomInput) => eventTypeCustomInput.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 +69,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", From 103228cf8452110f86d59b99e30b3231cb1eaeae Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 21 Apr 2022 01:15:58 +0200 Subject: [PATCH 14/24] feat: destination calendars ready --- README.md | 1 - pages/api/destination-calendars/[id].ts | 101 +++++++++++++---------- pages/api/destination-calendars/index.ts | 7 +- 3 files changed, 62 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 480973762b..844008a152 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,6 @@ tests/endpoint/resource.new.test.ts - Create new resource ## Models missing userId relation - daily-event-references -- destination-calendars ## Models from database that are not exposed diff --git a/pages/api/destination-calendars/[id].ts b/pages/api/destination-calendars/[id].ts index ef7712e525..62eb85810c 100644 --- a/pages/api/destination-calendars/[id].ts +++ b/pages/api/destination-calendars/[id].ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { DestinationCalendarResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaDestinationCalendarBodyParams, schemaDestinationCalendarPublic, @@ -96,53 +97,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 = getCalcomUserId(res); + 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)) { + 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; + } + } else res.status(401).json({ message: "Unauthorized" }); } export default withMiddleware("HTTP_GET_DELETE_PATCH")( diff --git a/pages/api/destination-calendars/index.ts b/pages/api/destination-calendars/index.ts index 3980b3e203..2b904dbc93 100644 --- a/pages/api/destination-calendars/index.ts +++ b/pages/api/destination-calendars/index.ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { DestinationCalendarResponse, DestinationCalendarsResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaDestinationCalendarBodyParams, schemaDestinationCalendarPublic, @@ -45,8 +46,10 @@ async function createOrlistAllDestinationCalendars( res: NextApiResponse ) { const { method } = req; + const userId = getCalcomUserId(res); + 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 +64,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) From ccd8637ae6601b04af0114db136fa6c63b2587d9 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 21 Apr 2022 01:30:47 +0200 Subject: [PATCH 15/24] feat: all endpoints safe --- README.md | 17 ++-- pages/api/daily-event-references/[id].ts | 105 +++++++++++++--------- pages/api/daily-event-references/index.ts | 9 +- 3 files changed, 77 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index 844008a152..9bcadef81e 100644 --- a/README.md +++ b/README.md @@ -139,11 +139,6 @@ tests/endpoint/resource.new.test.ts - Create new resource | teams | ✅ | ✅ | ✅ | ✅ | ✅ | | users | ✅ | 👤[1] | ✅ | ✅ | ✅ | -## Models missing userId relation - -- daily-event-references - - ## Models from database that are not exposed mostly because they're deemed too sensitive can be revisited if needed. most are expected to be used via cal's webapp. @@ -154,7 +149,7 @@ mostly because they're deemed too sensitive can be revisited if needed. most are - [ ] ResetPasswordRequest - [ ] VerificationToken - [ ] ReminderMail -- [ ] + ## Documentation (OpenAPI) You will see that each endpoint has a comment at the top with the annotation `@swagger` with the documentation of the endpoint, **please update it if you change the code!** This is what auto-generates the OpenAPI spec by collecting the YAML in each endpoint and parsing it in /docs alongside the json-schema (auto-generated from prisma package, not added to code but manually for now, need to fix later) @@ -171,7 +166,11 @@ in order to build and deploy properly. ## Envirorment variables -DATABASE_URL= -API_KEY_PREFIX=cal_# This can be changed per envirorment so cal_test_ for staging for example. +### Required -If you're self-hosting under our commercial license, you can use any prefix you want for api keys. either leave the default cal_ (not providing any envirorment variable) or modify it +DATABASE_URL=DATABASE_URL="postgresql://postgres:@localhost:5450/calendso" + +## Optional + +API_KEY_PREFIX=cal_# This can be changed per envirorment so cal_test_ for staging for example. +> If you're self-hosting under our commercial license, you can use any prefix you want for api keys. either leave the default cal_ (not providing any envirorment variable) or modify it diff --git a/pages/api/daily-event-references/[id].ts b/pages/api/daily-event-references/[id].ts index 17d6ced278..089e21610b 100644 --- a/pages/api/daily-event-references/[id].ts +++ b/pages/api/daily-event-references/[id].ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { DailyEventReferenceResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaDailyEventReferenceBodyParams, schemaDailyEventReferencePublic, @@ -96,53 +97,69 @@ 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 = getCalcomUserId(res); + 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)) { + 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; + } + } else res.status(401).json({ message: "Unauthorized" }); } export default withMiddleware("HTTP_GET_DELETE_PATCH")( diff --git a/pages/api/daily-event-references/index.ts b/pages/api/daily-event-references/index.ts index e3a90d6f03..8b00334b1e 100644 --- a/pages/api/daily-event-references/index.ts +++ b/pages/api/daily-event-references/index.ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { DailyEventReferenceResponse, DailyEventReferencesResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaDailyEventReferenceBodyParams, schemaDailyEventReferencePublic, @@ -45,8 +46,14 @@ async function createOrlistAllDailyEventReferences( res: NextApiResponse ) { const { method } = req; + const userId = getCalcomUserId(res); + 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) ); From 00bd2ed6e1030479abb55f58b55681c5e0c543f1 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Thu, 21 Apr 2022 01:31:36 +0200 Subject: [PATCH 16/24] remove old tests for now, add new tests later --- tests/bookings/[id]/booking.id.edit.test.ts | 116 ------------------ tests/bookings/[id]/booking.id.index.test.ts | 84 ------------- tests/bookings/booking.index.test.ts | 39 ------ tests/bookings/booking.new.test.ts | 77 ------------ .../[id]/event-type.id.edit.test.ts | 116 ------------------ .../[id]/event-type.id.index.test.ts | 75 ----------- tests/event-types/event-type.index.test.ts | 32 ----- tests/event-types/event-type.new.test.ts | 70 ----------- tests/teams/[id]/team.id.edit.test.ts | 107 ---------------- tests/teams/[id]/team.id.index.test.ts | 75 ----------- tests/users/[id]/user.id.edit.test.ts | 116 ------------------ tests/users/[id]/user.id.index.test.ts | 83 ------------- 12 files changed, 990 deletions(-) delete mode 100644 tests/bookings/[id]/booking.id.edit.test.ts delete mode 100644 tests/bookings/[id]/booking.id.index.test.ts delete mode 100644 tests/bookings/booking.index.test.ts delete mode 100644 tests/bookings/booking.new.test.ts delete mode 100644 tests/event-types/[id]/event-type.id.edit.test.ts delete mode 100644 tests/event-types/[id]/event-type.id.index.test.ts delete mode 100644 tests/event-types/event-type.index.test.ts delete mode 100644 tests/event-types/event-type.new.test.ts delete mode 100644 tests/teams/[id]/team.id.edit.test.ts delete mode 100644 tests/teams/[id]/team.id.index.test.ts delete mode 100644 tests/users/[id]/user.id.edit.test.ts delete mode 100644 tests/users/[id]/user.id.index.test.ts diff --git a/tests/bookings/[id]/booking.id.edit.test.ts b/tests/bookings/[id]/booking.id.edit.test.ts deleted file mode 100644 index 8bf32eb0e5..0000000000 --- a/tests/bookings/[id]/booking.id.edit.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import handleBookingEdit from "@api/bookings/[id]/edit"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -describe("PATCH /api/bookings/[id]/edit with valid id and body updates an booking", () => { - it("returns a message with the specified bookings", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "2", - }, - body: { - title: "Updated title", - slug: "updated-slug", - length: 1, - }, - }); - const booking = await prisma.booking.findUnique({ where: { id: parseInt(req.query.id) } }); - await handleBookingEdit(req, res); - - expect(res._getStatusCode()).toBe(200); - if (booking) booking.title = "Updated title"; - expect(JSON.parse(res._getData())).toStrictEqual({ data: booking }); - }); -}); - -describe("PATCH /api/bookings/[id]/edit with invalid id returns 404", () => { - it("returns a message with the specified bookings", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "0", - }, - body: { - title: "Updated title", - slug: "updated-slug", - length: 1, - }, - }); - const booking = await prisma.booking.findUnique({ where: { id: parseInt(req.query.id) } }); - await handleBookingEdit(req, res); - - expect(res._getStatusCode()).toBe(404); - if (booking) booking.title = "Updated title"; - expect(JSON.parse(res._getData())).toStrictEqual({ - error: { - clientVersion: "3.10.0", - code: "P2025", - meta: { - cause: "Record to update not found.", - }, - }, - message: "Event type with ID 0 not found and wasn't updated", - }); - }); -}); - -describe("PATCH /api/bookings/[id]/edit with valid id and no body returns 400 error and zod validation errors", () => { - it("returns a message with the specified bookings", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "2", - }, - }); - await handleBookingEdit(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "invalid_type", - expected: "string", - message: "Required", - path: ["title"], - received: "undefined", - }, - { - code: "invalid_type", - expected: "string", - message: "Required", - path: ["slug"], - received: "undefined", - }, - { - code: "invalid_type", - expected: "number", - message: "Required", - path: ["length"], - received: "undefined", - }, - ]); - }); -}); - -describe("POST /api/bookings/[id]/edit fails, only PATCH allowed", () => { - it("returns a message with the specified bookings", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "1", - }, - body: { - title: "Updated title", - slug: "updated-slug", - length: 1, - }, - }); - await handleBookingEdit(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ - message: "Only PATCH Method allowed for updating bookings", - }); - }); -}); diff --git a/tests/bookings/[id]/booking.id.index.test.ts b/tests/bookings/[id]/booking.id.index.test.ts deleted file mode 100644 index 4a2ff0ca0c..0000000000 --- a/tests/bookings/[id]/booking.id.index.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import handleBooking from "@api/bookings/[id]"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -import { stringifyISODate } from "@lib/utils/stringifyISODate"; - -describe("GET /api/bookings/[id] with valid id as string returns an booking", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: "1", - }, - }); - const booking = await prisma.booking.findUnique({ where: { id: 1 } }); - await handleBooking(req, res); - - expect(res._getStatusCode()).toBe(200); - expect(JSON.parse(res._getData())).toEqual({ - data: { - ...booking, - createdAt: stringifyISODate(booking?.createdAt), - startTime: stringifyISODate(booking?.startTime), - endTime: stringifyISODate(booking?.endTime), - }, - }); - }); -}); - -// This can never happen under our normal nextjs setup where query is always a string | string[]. -// But seemed a good example for testing an error validation -describe("GET /api/bookings/[id] errors if query id is number, requires a string", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: 1, // passing query as a number, which should fail as nextjs will try to parse it as a string - }, - }); - await handleBooking(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "invalid_type", - expected: "string", - received: "number", - path: ["id"], - message: "Expected string, received number", - }, - ]); - }); -}); - -describe("GET /api/bookings/[id] an id not present in db like 0, throws 404 not found", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: "0", // There's no booking type with id 0 - }, - }); - await handleBooking(req, res); - - expect(res._getStatusCode()).toBe(404); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Event type not found" }); - }); -}); - -describe("POST /api/bookings/[id] fails, only GET allowed", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "1", - }, - }); - await handleBooking(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" }); - }); -}); diff --git a/tests/bookings/booking.index.test.ts b/tests/bookings/booking.index.test.ts deleted file mode 100644 index 957b749b88..0000000000 --- a/tests/bookings/booking.index.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import handleApiKeys from "@api/api-keys"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -import { stringifyISODate } from "@lib/utils/stringifyISODate"; - -describe("GET /api/api-keys without any params", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "GET", - query: {}, - }); - let apiKeys = await prisma.apiKey.findMany(); - await handleApiKeys(req, res); - - expect(res._getStatusCode()).toBe(200); - apiKeys = apiKeys.map( - (apiKey) => - (apiKey = { - ...apiKey, - createdAt: stringifyISODate(apiKey?.createdAt), - expiresAt: stringifyISODate(apiKey?.expiresAt), - }) - ); - expect(JSON.parse(res._getData())).toStrictEqual(JSON.parse(JSON.stringify({ data: { ...apiKeys } }))); - }); -}); - -describe("POST /api/api-keys/ fails, only GET allowed", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - }); - await handleApiKeys(req, res); - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" }); - }); -}); diff --git a/tests/bookings/booking.new.test.ts b/tests/bookings/booking.new.test.ts deleted file mode 100644 index 339b4c146b..0000000000 --- a/tests/bookings/booking.new.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import handleNewApiKey from "@api/api-keys/new"; -import { createMocks } from "node-mocks-http"; - -describe("POST /api/api-keys/new with a note", () => { - it("returns a 201, and the created api key", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - body: { - note: "Updated note", - }, - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(201); - expect(JSON.parse(res._getData()).data.note).toStrictEqual("Updated note"); - }); -}); - -describe("POST /api/api-keys/new with a slug param", () => { - it("returns error 400, and the details about invalid slug body param", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - body: { - note: "Updated note", - slug: "slug", - }, - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "unrecognized_keys", - keys: ["slug"], - message: "Unrecognized key(s) in object: 'slug'", - path: [], - }, - ]); - }); -}); - -describe("GET /api/api-keys/new fails, only POST allowed", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "GET", // This POST method is not allowed - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ error: "Only POST Method allowed" }); - }); -}); - -// FIXME: test 405 when prisma fails look for how to test prisma errors -describe("GET /api/api-keys/new fails, only POST allowed", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - body: { - nonExistentParam: true, - // note: '123', - // slug: 12, - }, - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "unrecognized_keys", - keys: ["nonExistentParam"], - message: "Unrecognized key(s) in object: 'nonExistentParam'", - path: [], - }, - ]); - }); -}); diff --git a/tests/event-types/[id]/event-type.id.edit.test.ts b/tests/event-types/[id]/event-type.id.edit.test.ts deleted file mode 100644 index e88bcb9b49..0000000000 --- a/tests/event-types/[id]/event-type.id.edit.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import handleEventTypeEdit from "@api/event-types/[id]/edit"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -describe("PATCH /api/event-types/[id]/edit with valid id and body updates an event-type", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "2", - }, - body: { - title: "Updated title", - slug: "updated-slug", - length: 1, - }, - }); - const event = await prisma.eventType.findUnique({ where: { id: parseInt(req.query.id) } }); - await handleEventTypeEdit(req, res); - - expect(res._getStatusCode()).toBe(200); - if (event) event.title = "Updated title"; - expect(JSON.parse(res._getData())).toStrictEqual({ data: event }); - }); -}); - -describe("PATCH /api/event-types/[id]/edit with invalid id returns 404", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "0", - }, - body: { - title: "Updated title", - slug: "updated-slug", - length: 1, - }, - }); - const event = await prisma.eventType.findUnique({ where: { id: parseInt(req.query.id) } }); - await handleEventTypeEdit(req, res); - - expect(res._getStatusCode()).toBe(404); - if (event) event.title = "Updated title"; - expect(JSON.parse(res._getData())).toStrictEqual({ - error: { - clientVersion: "3.10.0", - code: "P2025", - meta: { - cause: "Record to update not found.", - }, - }, - message: "Event type with ID 0 not found and wasn't updated", - }); - }); -}); - -describe("PATCH /api/event-types/[id]/edit with valid id and no body returns 400 error and zod validation errors", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "2", - }, - }); - await handleEventTypeEdit(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "invalid_type", - expected: "string", - message: "Required", - path: ["title"], - received: "undefined", - }, - { - code: "invalid_type", - expected: "string", - message: "Required", - path: ["slug"], - received: "undefined", - }, - { - code: "invalid_type", - expected: "number", - message: "Required", - path: ["length"], - received: "undefined", - }, - ]); - }); -}); - -describe("POST /api/event-types/[id]/edit fails, only PATCH allowed", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "1", - }, - body: { - title: "Updated title", - slug: "updated-slug", - length: 1, - }, - }); - await handleEventTypeEdit(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ - message: "Only PATCH Method allowed for updating event-types", - }); - }); -}); diff --git a/tests/event-types/[id]/event-type.id.index.test.ts b/tests/event-types/[id]/event-type.id.index.test.ts deleted file mode 100644 index bb54d5963f..0000000000 --- a/tests/event-types/[id]/event-type.id.index.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import handleEventType from "@api/event-types/[id]"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -describe("GET /api/event-types/[id] with valid id as string returns an event-type", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: "1", - }, - }); - const event = await prisma.eventType.findUnique({ where: { id: 1 } }); - await handleEventType(req, res); - - expect(res._getStatusCode()).toBe(200); - expect(JSON.parse(res._getData())).toStrictEqual({ data: event }); - }); -}); - -// This can never happen under our normal nextjs setup where query is always a string | string[]. -// But seemed a good example for testing an error validation -describe("GET /api/event-types/[id] errors if query id is number, requires a string", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: 1, // passing query as a number, which should fail as nextjs will try to parse it as a string - }, - }); - await handleEventType(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "invalid_type", - expected: "string", - received: "number", - path: ["id"], - message: "Expected string, received number", - }, - ]); - }); -}); - -describe("GET /api/event-types/[id] an id not present in db like 0, throws 404 not found", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: "0", // There's no event type with id 0 - }, - }); - await handleEventType(req, res); - - expect(res._getStatusCode()).toBe(404); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Event type not found" }); - }); -}); - -describe("POST /api/event-types/[id] fails, only GET allowed", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "1", - }, - }); - await handleEventType(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" }); - }); -}); diff --git a/tests/event-types/event-type.index.test.ts b/tests/event-types/event-type.index.test.ts deleted file mode 100644 index 7a63a59a5d..0000000000 --- a/tests/event-types/event-type.index.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import handleApiKeys from "@api/event-types"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -// import {stringifyISODate} from "@lib/utils/stringifyISODate"; - -describe("GET /api/event-types without any params", () => { - it("returns a message with the specified eventTypes", async () => { - const { req, res } = createMocks({ - method: "GET", - query: {}, - }); - const eventTypes = await prisma.eventType.findMany(); - await handleApiKeys(req, res); - - expect(res._getStatusCode()).toBe(200); - // eventTypes = eventTypes.map(eventType => (eventType = {...eventType, createdAt: stringifyISODate(eventType?.createdAt), expiresAt: stringifyISODate(eventType?.expiresAt)})); - expect(JSON.parse(res._getData())).toStrictEqual(JSON.parse(JSON.stringify({ data: { ...eventTypes } }))); - }); -}); - -describe("POST /api/event-types/ fails, only GET allowed", () => { - it("returns a message with the specified eventTypes", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - }); - await handleApiKeys(req, res); - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" }); - }); -}); diff --git a/tests/event-types/event-type.new.test.ts b/tests/event-types/event-type.new.test.ts deleted file mode 100644 index a79209ec03..0000000000 --- a/tests/event-types/event-type.new.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import handleNewApiKey from "@api/api-keys/new"; -import { createMocks } from "node-mocks-http"; - -describe("POST /api/api-keys/new with a note", () => { - it("returns a 201, and the created api key", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - body: { - note: "Updated note", - }, - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(201); - expect(JSON.parse(res._getData()).data.note).toStrictEqual("Updated note"); - }); -}); - -describe("POST /api/api-keys/new with a slug param", () => { - it("returns error 400, and the details about invalid slug body param", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - body: { - note: "Updated note", - slug: "slug", - }, - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "unrecognized_keys", - keys: ["slug"], - message: "Unrecognized key(s) in object: 'slug'", - path: [], - }, - ]); - }); -}); - -describe("GET /api/api-keys/new fails, only POST allowed", () => { - it("returns a message with the specified apiKeys", async () => { - const { req, res } = createMocks({ - method: "GET", // This POST method is not allowed - }); - await handleNewApiKey(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ error: "Only POST Method allowed" }); - }); -}); - -// FIXME: test 405 when prisma fails look for how to test prisma errors -// describe("GET /api/api-keys/new fails, only POST allowed", () => { -// it("returns a message with the specified apiKeys", async () => { -// const { req, res } = createMocks({ -// method: "POST", // This POST method is not allowed -// body: { -// fail: true -// // note: '123', -// // slug: 12, -// }, -// }); -// await handleNewApiKey(req, res); - -// expect(res._getStatusCode()).toBe(400); -// expect(JSON.parse(res._getData())).toStrictEqual({ error: "Only POST Method allowed" }); -// }); -// }); diff --git a/tests/teams/[id]/team.id.edit.test.ts b/tests/teams/[id]/team.id.edit.test.ts deleted file mode 100644 index 101deaa06e..0000000000 --- a/tests/teams/[id]/team.id.edit.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import handleTeamEdit from "@api/teams/[id]/edit"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -describe("PATCH /api/teams/[id]/edit with valid id and body updates a team", () => { - it("returns a message with the specified teams", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "1", - }, - body: { - name: "Updated team", - slug: "updated-team", - }, - }); - const team = await prisma.team.findUnique({ where: { id: parseInt(req.query.id) } }); - await handleTeamEdit(req, res); - - expect(res._getStatusCode()).toBe(200); - // if (team) team.name = "Updated name"; - expect(JSON.parse(res._getData())).toStrictEqual({ data: team }); - }); -}); - -describe("PATCH /api/teams/[id]/edit with invalid id returns 404", () => { - it("returns a message with the specified teams", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "0", - }, - body: { - name: "Updated name", - slug: "updated-slug", - }, - }); - const team = await prisma.team.findUnique({ where: { id: parseInt(req.query.id) } }); - await handleTeamEdit(req, res); - - expect(res._getStatusCode()).toBe(404); - expect(JSON.parse(res._getData())).toStrictEqual({ - error: { - clientVersion: "3.10.0", - code: "P2025", - meta: { - cause: "Record to update not found.", - }, - }, - message: "Event type with ID 0 not found and wasn't updated", - }); - }); -}); - -describe("PATCH /api/teams/[id]/edit with valid id and no body returns 400 error and zod validation errors", () => { - it("returns a message with the specified teams", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "2", - }, - }); - await handleTeamEdit(req, res); - - expect(res._getStatusCode()).toBe(400); - - // Ugly parsing of zod validation errors, not for final production but works for testing - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "invalid_type", - expected: "string", - message: "Required", - path: ["slug"], - received: "undefined", - }, - { - code: "invalid_type", - expected: "string", - message: "Required", - path: ["name"], - received: "undefined", - }, - ]); - }); -}); - -describe("POST /api/teams/[id]/edit fails, only PATCH allowed", () => { - it("returns a message with the specified teams", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "1", - }, - body: { - name: "Updated name", - slug: "updated-slug", - }, - }); - await handleTeamEdit(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ - message: "Only PATCH Method allowed for updating teams", - }); - }); -}); diff --git a/tests/teams/[id]/team.id.index.test.ts b/tests/teams/[id]/team.id.index.test.ts deleted file mode 100644 index 016f7ec604..0000000000 --- a/tests/teams/[id]/team.id.index.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import handleTeam from "@api/teams/[id]"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -describe("GET /api/teams/[id] with valid id as string returns an team-type", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: "1", - }, - }); - const team = await prisma.team.findUnique({ where: { id: 1 } }); - await handleTeam(req, res); - - expect(res._getStatusCode()).toBe(200); - expect(JSON.parse(res._getData())).toStrictEqual({ data: team }); - }); -}); - -// This can never happen under our normal nextjs setup where query is always a string | string[]. -// But seemed a good example for testing an error validation -describe("GET /api/teams/[id] errors if query id is number, requires a string", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: 1, // passing query as a number, which should fail as nextjs will try to parse it as a string - }, - }); - await handleTeam(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "invalid_type", - expected: "string", - received: "number", - path: ["id"], - message: "Expected string, received number", - }, - ]); - }); -}); - -describe("GET /api/teams/[id] an id not present in db like 0, throws 404 not found", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: "0", // There's no team type with id 0 - }, - }); - await handleTeam(req, res); - - expect(res._getStatusCode()).toBe(404); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Event type not found" }); - }); -}); - -describe("POST /api/teams/[id] fails, only GET allowed", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "1", - }, - }); - await handleTeam(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" }); - }); -}); diff --git a/tests/users/[id]/user.id.edit.test.ts b/tests/users/[id]/user.id.edit.test.ts deleted file mode 100644 index e88bcb9b49..0000000000 --- a/tests/users/[id]/user.id.edit.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import handleEventTypeEdit from "@api/event-types/[id]/edit"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -describe("PATCH /api/event-types/[id]/edit with valid id and body updates an event-type", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "2", - }, - body: { - title: "Updated title", - slug: "updated-slug", - length: 1, - }, - }); - const event = await prisma.eventType.findUnique({ where: { id: parseInt(req.query.id) } }); - await handleEventTypeEdit(req, res); - - expect(res._getStatusCode()).toBe(200); - if (event) event.title = "Updated title"; - expect(JSON.parse(res._getData())).toStrictEqual({ data: event }); - }); -}); - -describe("PATCH /api/event-types/[id]/edit with invalid id returns 404", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "0", - }, - body: { - title: "Updated title", - slug: "updated-slug", - length: 1, - }, - }); - const event = await prisma.eventType.findUnique({ where: { id: parseInt(req.query.id) } }); - await handleEventTypeEdit(req, res); - - expect(res._getStatusCode()).toBe(404); - if (event) event.title = "Updated title"; - expect(JSON.parse(res._getData())).toStrictEqual({ - error: { - clientVersion: "3.10.0", - code: "P2025", - meta: { - cause: "Record to update not found.", - }, - }, - message: "Event type with ID 0 not found and wasn't updated", - }); - }); -}); - -describe("PATCH /api/event-types/[id]/edit with valid id and no body returns 400 error and zod validation errors", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "PATCH", - query: { - id: "2", - }, - }); - await handleEventTypeEdit(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "invalid_type", - expected: "string", - message: "Required", - path: ["title"], - received: "undefined", - }, - { - code: "invalid_type", - expected: "string", - message: "Required", - path: ["slug"], - received: "undefined", - }, - { - code: "invalid_type", - expected: "number", - message: "Required", - path: ["length"], - received: "undefined", - }, - ]); - }); -}); - -describe("POST /api/event-types/[id]/edit fails, only PATCH allowed", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "1", - }, - body: { - title: "Updated title", - slug: "updated-slug", - length: 1, - }, - }); - await handleEventTypeEdit(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ - message: "Only PATCH Method allowed for updating event-types", - }); - }); -}); diff --git a/tests/users/[id]/user.id.index.test.ts b/tests/users/[id]/user.id.index.test.ts deleted file mode 100644 index bf79c38143..0000000000 --- a/tests/users/[id]/user.id.index.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import handleUser from "@api/users/[id]"; -import { createMocks } from "node-mocks-http"; - -import prisma from "@calcom/prisma"; - -import { stringifyISODate } from "@lib/utils/stringifyISODate"; - -describe("GET /api/users/[id] with valid id as string returns an user-type", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: "1", - }, - }); - const user = await prisma.user.findUnique({ where: { id: 1 } }); - await handleUser(req, res); - - expect(res._getStatusCode()).toBe(200); - expect(JSON.parse(res._getData())).toEqual({ - data: { - ...user, - createdDate: stringifyISODate(user?.createdDate), - emailVerified: stringifyISODate(user?.emailVerified), - }, - }); - }); -}); - -// This can never happen under our normal nextjs setup where query is always a string | string[]. -// But seemed a good example for testing an error validation -describe("GET /api/users/[id] errors if query id is number, requires a string", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: 1, // passing query as a number, which should fail as nextjs will try to parse it as a string - }, - }); - await handleUser(req, res); - - expect(res._getStatusCode()).toBe(400); - expect(JSON.parse(res._getData())).toStrictEqual([ - { - code: "invalid_type", - expected: "string", - received: "number", - path: ["id"], - message: "Expected string, received number", - }, - ]); - }); -}); - -describe("GET /api/users/[id] an id not present in db like 0, throws 404 not found", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "GET", - query: { - id: "0", // There's no user type with id 0 - }, - }); - await handleUser(req, res); - - expect(res._getStatusCode()).toBe(404); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Event type not found" }); - }); -}); - -describe("POST /api/users/[id] fails, only GET allowed", () => { - it("returns a message with the specified events", async () => { - const { req, res } = createMocks({ - method: "POST", // This POST method is not allowed - query: { - id: "1", - }, - }); - await handleUser(req, res); - - expect(res._getStatusCode()).toBe(405); - expect(JSON.parse(res._getData())).toStrictEqual({ message: "Only GET Method allowed" }); - }); -}); From be3bcf2bf00313efc5761aa962138b5415d13aa0 Mon Sep 17 00:00:00 2001 From: zomars Date: Thu, 21 Apr 2022 19:36:33 -0600 Subject: [PATCH 17/24] Refactoring and fixes --- .husky/pre-commit | 4 --- .prettierrc.js | 1 - babel.config.js | 3 -- lib/helpers/verifyApiKey.ts | 36 ++++++++++++--------- lib/utils/getCalcomUserId.ts | 3 -- package.json | 13 ++------ pages/api/attendees/[id].ts | 3 +- pages/api/attendees/index.ts | 5 ++- pages/api/availabilities/[id].ts | 3 +- pages/api/availabilities/index.ts | 3 +- pages/api/booking-references/[id].ts | 3 +- pages/api/booking-references/index.ts | 5 ++- pages/api/bookings/[id].ts | 3 +- pages/api/bookings/index.ts | 3 +- pages/api/daily-event-references/[id].ts | 3 +- pages/api/daily-event-references/index.ts | 3 +- pages/api/destination-calendars/[id].ts | 3 +- pages/api/destination-calendars/index.ts | 3 +- pages/api/event-type-custom-inputs/[id].ts | 3 +- pages/api/event-type-custom-inputs/index.ts | 2 +- pages/api/event-types/[id].ts | 3 +- pages/api/event-types/index.ts | 3 +- pages/api/memberships/[id].ts | 3 +- pages/api/memberships/index.ts | 3 +- pages/api/payments/[id].ts | 3 +- pages/api/payments/index.ts | 5 ++- pages/api/schedules/[id].ts | 3 +- pages/api/schedules/index.ts | 3 +- pages/api/selected-calendars/[id].ts | 3 +- pages/api/selected-calendars/index.ts | 3 +- pages/api/teams/[id].ts | 3 +- pages/api/teams/index.ts | 3 +- pages/api/users/[id].ts | 3 +- pages/api/users/index.ts | 3 +- tsconfig.json | 22 ++++++------- 35 files changed, 64 insertions(+), 107 deletions(-) delete mode 100755 .husky/pre-commit delete mode 100644 .prettierrc.js delete mode 100644 babel.config.js delete mode 100644 lib/utils/getCalcomUserId.ts 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 0ee197456c..0f70c88a8e 100644 --- a/lib/helpers/verifyApiKey.ts +++ b/lib/helpers/verifyApiKey.ts @@ -1,8 +1,17 @@ +import type { IncomingMessage } from "http"; +import type { NextApiRequest, NextApiResponse } from "next"; import { NextMiddleware } from "next-api-middleware"; import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys"; import prisma from "@calcom/prisma"; +/** @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 API key is not expired, could be extracted if reused. but not for now. export const dateInPast = function (date: Date) { const now = new Date(); @@ -12,24 +21,21 @@ export const dateInPast = function (date: Date) { }; // This verifies the API key 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" }); +export const verifyApiKey: NextMiddleware = async (req: NextApiRequest, res: NextApiResponse, next) => { + if (!req.query.apiKey) return res.status(401).json({ message: "No api key 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. - if (apiKey.userId) 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 api key is not valid" }); + if (apiKey.expiresAt && dateInPast(apiKey.expiresAt)) { + return res.status(401).json({ error: "This api key is expired" }); + } + if (!apiKey.userId) return res.status(404).json({ error: "No user found for this api key" }); + /* We save the user id in the request for later use */ + req.userId = apiKey.userId; + await next(); }; 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/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..3eba0891f2 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 ) { 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 = getCalcomUserId(res); + const userId = req.userId; const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, include: { bookings: true }, diff --git a/pages/api/availabilities/[id].ts b/pages/api/availabilities/[id].ts index bdb1215f74..546fbe0ce1 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, @@ -97,7 +96,7 @@ 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 = 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)) { diff --git a/pages/api/availabilities/index.ts b/pages/api/availabilities/index.ts index 63ae75db49..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"; /** @@ -47,7 +46,7 @@ async function createOrlistAllAvailabilities( res: NextApiResponse ) { const { method } = req; - const userId = 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 9a1b40089b..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 = 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 9ceedeed30..03bc700596 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 = 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 = getCalcomUserId(res); + const userId = req.userId; const userWithBookings = await prisma.user.findUnique({ where: { id: userId }, include: { bookings: true }, diff --git a/pages/api/bookings/[id].ts b/pages/api/bookings/[id].ts index af6a379158..f40ae3ccbd 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,7 +90,7 @@ export async function bookingById(req: NextApiRequest, res: NextApiResponse ) { const { method } = req; - const userId = 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 089e21610b..993e47ed57 100644 --- a/pages/api/daily-event-references/[id].ts +++ b/pages/api/daily-event-references/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { DailyEventReferenceResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaDailyEventReferenceBodyParams, schemaDailyEventReferencePublic, @@ -97,7 +96,7 @@ 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 = getCalcomUserId(res); + 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({ diff --git a/pages/api/daily-event-references/index.ts b/pages/api/daily-event-references/index.ts index 8b00334b1e..7b216d0040 100644 --- a/pages/api/daily-event-references/index.ts +++ b/pages/api/daily-event-references/index.ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { DailyEventReferenceResponse, DailyEventReferencesResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaDailyEventReferenceBodyParams, schemaDailyEventReferencePublic, @@ -46,7 +45,7 @@ async function createOrlistAllDailyEventReferences( res: NextApiResponse ) { const { method } = req; - const userId = getCalcomUserId(res); + const userId = req.userId; const userBookings = await prisma.booking.findMany({ where: { userId } }); const userBookingIds = userBookings.map((booking) => booking.id); diff --git a/pages/api/destination-calendars/[id].ts b/pages/api/destination-calendars/[id].ts index 62eb85810c..579ba83482 100644 --- a/pages/api/destination-calendars/[id].ts +++ b/pages/api/destination-calendars/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { DestinationCalendarResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaDestinationCalendarBodyParams, schemaDestinationCalendarPublic, @@ -97,7 +96,7 @@ 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 = getCalcomUserId(res); + 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. diff --git a/pages/api/destination-calendars/index.ts b/pages/api/destination-calendars/index.ts index 2b904dbc93..b3bdcaab57 100644 --- a/pages/api/destination-calendars/index.ts +++ b/pages/api/destination-calendars/index.ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { DestinationCalendarResponse, DestinationCalendarsResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaDestinationCalendarBodyParams, schemaDestinationCalendarPublic, @@ -46,7 +45,7 @@ async function createOrlistAllDestinationCalendars( res: NextApiResponse ) { const { method } = req; - const userId = getCalcomUserId(res); + const userId = req.userId; if (method === "GET") { const data = await prisma.destinationCalendar.findMany({ where: { userId } }); diff --git a/pages/api/event-type-custom-inputs/[id].ts b/pages/api/event-type-custom-inputs/[id].ts index 5a00436361..5ff11ff884 100644 --- a/pages/api/event-type-custom-inputs/[id].ts +++ b/pages/api/event-type-custom-inputs/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { EventTypeCustomInputResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaEventTypeCustomInputBodyParams, schemaEventTypeCustomInputPublic, @@ -94,7 +93,7 @@ async function eventTypeById(req: NextApiRequest, res: NextApiResponse eventType.id); const userEventTypeCustomInputs = await prisma.eventTypeCustomInput.findMany({ diff --git a/pages/api/event-type-custom-inputs/index.ts b/pages/api/event-type-custom-inputs/index.ts index e6c0c852bf..82c23f8593 100644 --- a/pages/api/event-type-custom-inputs/index.ts +++ b/pages/api/event-type-custom-inputs/index.ts @@ -45,7 +45,7 @@ async function createOrlistAllEventTypeCustomInputs( res: NextApiResponse ) { const { method } = req; - const userId = getCalcomUserId(res); + const userId = req.userId; const data = await prisma.eventType.findMany({ where: { userId } }); const userEventTypes = data.map((eventType) => eventType.id); // const userEventTypeCustomInputs = await prisma.eventTypeCustomInput.findMany({ diff --git a/pages/api/event-types/[id].ts b/pages/api/event-types/[id].ts index dc7535cd5a..80d4f95bb6 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 { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaEventTypeBodyParams, schemaEventTypePublic } from "@lib/validations/event-type"; import { schemaQueryIdParseInt, @@ -97,7 +96,7 @@ export async function eventTypeById(req: NextApiRequest, res: NextApiResponse eventType.id); if (userEventTypes.includes(safeQuery.data.id)) { diff --git a/pages/api/event-types/index.ts b/pages/api/event-types/index.ts index fc6a2a35f7..3135d9e866 100644 --- a/pages/api/event-types/index.ts +++ b/pages/api/event-types/index.ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { EventTypeResponse, EventTypesResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaEventTypeBodyParams, schemaEventTypePublic } from "@lib/validations/event-type"; /** @@ -47,7 +46,7 @@ async function createOrlistAllEventTypes( res: NextApiResponse ) { const { method } = req; - const userId = getCalcomUserId(res); + const userId = req.userId; if (method === "GET") { const data = await prisma.eventType.findMany({ where: { userId } }); diff --git a/pages/api/memberships/[id].ts b/pages/api/memberships/[id].ts index df62f89107..4c90122f70 100644 --- a/pages/api/memberships/[id].ts +++ b/pages/api/memberships/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { MembershipResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaMembershipBodyParams, schemaMembershipPublic } from "@lib/validations/membership"; import { schemaQueryIdAsString, withValidQueryIdString } from "@lib/validations/shared/queryIdString"; @@ -108,7 +107,7 @@ export async function membershipById(req: NextApiRequest, res: NextApiResponse ) { const { method } = req; - const userId = getCalcomUserId(res); + const userId = req.userId; if (method === "GET") { const data = await prisma.membership.findMany({ where: { userId } }); const memberships = data.map((membership) => schemaMembershipPublic.parse(membership)); diff --git a/pages/api/payments/[id].ts b/pages/api/payments/[id].ts index 295803ca76..9d7d28a184 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 = getCalcomUserId(res); + const userId = req.userId; if (safeQuery.success && method === "GET") { const userWithBookings = await prisma.user.findUnique({ diff --git a/pages/api/payments/index.ts b/pages/api/payments/index.ts index bb2c132c0c..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 = 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/schedules/[id].ts b/pages/api/schedules/[id].ts index 1b46e62269..e0b83f106b 100644 --- a/pages/api/schedules/[id].ts +++ b/pages/api/schedules/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { ScheduleResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaScheduleBodyParams, schemaSchedulePublic } from "@lib/validations/schedule"; import { schemaQueryIdParseInt, @@ -91,7 +90,7 @@ export async function scheduleById(req: NextApiRequest, res: NextApiResponse schedule.id); if (userScheduleIds.includes(safeQuery.data.id)) { diff --git a/pages/api/schedules/index.ts b/pages/api/schedules/index.ts index cb4eeaeb9d..bbdd1c8dbc 100644 --- a/pages/api/schedules/index.ts +++ b/pages/api/schedules/index.ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { ScheduleResponse, SchedulesResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaScheduleBodyParams, schemaSchedulePublic, withValidSchedule } from "@lib/validations/schedule"; /** @@ -43,7 +42,7 @@ async function createOrlistAllSchedules( res: NextApiResponse ) { const { method } = req; - const userId = getCalcomUserId(res); + const userId = req.userId; if (method === "GET") { const data = await prisma.schedule.findMany({ where: { userId } }); diff --git a/pages/api/selected-calendars/[id].ts b/pages/api/selected-calendars/[id].ts index 69cd9c059e..c2febd9c47 100644 --- a/pages/api/selected-calendars/[id].ts +++ b/pages/api/selected-calendars/[id].ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { SelectedCalendarResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaSelectedCalendarBodyParams, schemaSelectedCalendarPublic, @@ -132,7 +131,7 @@ export async function selectedCalendarById( 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 [paramUserId, integration, externalId] = safeQuery.data.id.split("_"); - const userId = getCalcomUserId(res); + const userId = req.userId; if (userId === parseInt(paramUserId)) { switch (method) { case "GET": diff --git a/pages/api/selected-calendars/index.ts b/pages/api/selected-calendars/index.ts index cb12a5dac7..0ccde36943 100644 --- a/pages/api/selected-calendars/index.ts +++ b/pages/api/selected-calendars/index.ts @@ -4,7 +4,6 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { SelectedCalendarResponse, SelectedCalendarsResponse } from "@lib/types"; -import { getCalcomUserId } from "@lib/utils/getCalcomUserId"; import { schemaSelectedCalendarBodyParams, schemaSelectedCalendarPublic, @@ -46,7 +45,7 @@ async function createOrlistAllSelectedCalendars( res: NextApiResponse ) { const { method } = req; - const userId = getCalcomUserId(res); + const userId = req.userId; if (method === "GET") { const data = await prisma.selectedCalendar.findMany({ where: { userId } }); diff --git a/pages/api/teams/[id].ts b/pages/api/teams/[id].ts index de14a27c3d..69a3a7091f 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,7 +90,7 @@ export async function teamById(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 }, diff --git a/pages/api/users/[id].ts b/pages/api/users/[id].ts index 5beaf442df..6dd4eb5f63 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,7 +90,7 @@ 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"] } From 20cef3b4dd0078d85dc6decc563353f50803c732 Mon Sep 17 00:00:00 2001 From: zomars Date: Fri, 22 Apr 2022 08:05:31 -0600 Subject: [PATCH 18/24] Uses inferred types --- lib/helpers/verifyApiKey.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/helpers/verifyApiKey.ts b/lib/helpers/verifyApiKey.ts index 0f70c88a8e..77eaf7e4cb 100644 --- a/lib/helpers/verifyApiKey.ts +++ b/lib/helpers/verifyApiKey.ts @@ -1,5 +1,4 @@ import type { IncomingMessage } from "http"; -import type { NextApiRequest, NextApiResponse } from "next"; import { NextMiddleware } from "next-api-middleware"; import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys"; @@ -21,7 +20,7 @@ export const dateInPast = function (date: Date) { }; // This verifies the API key and sets the user if it is valid. -export const verifyApiKey: NextMiddleware = async (req: NextApiRequest, res: NextApiResponse, next) => { +export const verifyApiKey: NextMiddleware = async (req, res, next) => { if (!req.query.apiKey) return res.status(401).json({ message: "No api key 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_", ""); From 368e6eb0fa83115ffeaf8d2105644ce65363184c Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Sat, 23 Apr 2022 02:05:56 +0200 Subject: [PATCH 19/24] fix: rename dateInPast -> dateNotInPast --- lib/helpers/verifyApiKey.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/helpers/verifyApiKey.ts b/lib/helpers/verifyApiKey.ts index 77eaf7e4cb..6a8c24df4e 100644 --- a/lib/helpers/verifyApiKey.ts +++ b/lib/helpers/verifyApiKey.ts @@ -12,7 +12,7 @@ declare module "next" { } // 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) { +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; @@ -30,7 +30,7 @@ export const verifyApiKey: NextMiddleware = async (req, res, 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 api key is not valid" }); - if (apiKey.expiresAt && dateInPast(apiKey.expiresAt)) { + if (apiKey.expiresAt && dateNotInPast(apiKey.expiresAt)) { return res.status(401).json({ error: "This api key is expired" }); } if (!apiKey.userId) return res.status(404).json({ error: "No user found for this api key" }); From 9cb2f9bc704a0bb2d60fd19f7289265686113870 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Sat, 23 Apr 2022 02:06:16 +0200 Subject: [PATCH 20/24] fix: clearer note about dropping metadata and locations in event-type --- lib/validations/event-type.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/validations/event-type.ts b/lib/validations/event-type.ts index ab24a9b0d1..119edcb248 100644 --- a/lib/validations/event-type.ts +++ b/lib/validations/event-type.ts @@ -12,7 +12,7 @@ const schemaEventTypeRequiredParams = z.object({ }); export const schemaEventTypeBodyParams = schemaEventTypeBaseBodyParams.merge(schemaEventTypeRequiredParams); -// Omitting those two (locations/ metadata) because the validations where choking at array and JSON object. add them later if needed +// @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({ From 307eddcbd528b24c6b6530f12176b1e4ac4db87e Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Sat, 23 Apr 2022 02:06:39 +0200 Subject: [PATCH 21/24] fix: invert 401 to throw early in attendees --- pages/api/attendees/[id].ts | 5 +++-- pages/api/attendees/index.ts | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/pages/api/attendees/[id].ts b/pages/api/attendees/[id].ts index 3eba0891f2..03133bf526 100644 --- a/pages/api/attendees/[id].ts +++ b/pages/api/attendees/[id].ts @@ -100,7 +100,8 @@ 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 @@ -151,7 +152,7 @@ export async function attendeeById(req: NextApiRequest, res: NextApiResponse 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({ @@ -99,7 +100,7 @@ async function createOrlistAllAttendees( error, }); } - } else res.status(401).json({ message: "Unauthorized" }); + } } else res.status(405).json({ message: `Method ${method} not allowed` }); } From 8d5605dc7b449018c04b07f4ab45e86a4193da30 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Sat, 23 Apr 2022 02:17:06 +0200 Subject: [PATCH 22/24] fix: move 401 to throw early in all endpoints --- pages/api/availabilities/[id].ts | 5 ++--- pages/api/booking-references/index.ts | 5 +++-- pages/api/bookings/[id].ts | 5 +++-- pages/api/daily-event-references/[id].ts | 6 ++++-- pages/api/destination-calendars/[id].ts | 5 +++-- pages/api/event-type-custom-inputs/[id].ts | 6 ++++-- pages/api/event-types/[id].ts | 3 ++- pages/api/memberships/[id].ts | 5 +++-- pages/api/payments/[id].ts | 6 +++--- pages/api/schedules/[id].ts | 5 +++-- pages/api/selected-calendars/[id].ts | 5 +++-- pages/api/teams/[id].ts | 5 +++-- pages/api/users/[id].ts | 5 +++-- 13 files changed, 39 insertions(+), 27 deletions(-) diff --git a/pages/api/availabilities/[id].ts b/pages/api/availabilities/[id].ts index 546fbe0ce1..7d5bfb8b91 100644 --- a/pages/api/availabilities/[id].ts +++ b/pages/api/availabilities/[id].ts @@ -99,7 +99,8 @@ export async function availabilityById(req: NextApiRequest, res: NextApiResponse 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 @@ -142,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/booking-references/index.ts b/pages/api/booking-references/index.ts index 03bc700596..74ae942dd2 100644 --- a/pages/api/booking-references/index.ts +++ b/pages/api/booking-references/index.ts @@ -80,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 }, }); @@ -96,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 f40ae3ccbd..9172b7dc90 100644 --- a/pages/api/bookings/[id].ts +++ b/pages/api/bookings/[id].ts @@ -97,7 +97,8 @@ 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 @@ -151,7 +152,7 @@ export async function bookingById(req: NextApiRequest, res: NextApiResponse dailyEventReference.id ); - if (userBookingDailyEventReferenceIds.includes(safeQuery.data.id)) { + if (!userBookingDailyEventReferenceIds.includes(safeQuery.data.id)) + res.status(401).json({ message: "Unauthorized" }); + else { switch (method) { case "GET": await prisma.dailyEventReference @@ -158,7 +160,7 @@ export async function dailyEventReferenceById( res.status(405).json({ message: "Method not allowed" }); break; } - } else res.status(401).json({ message: "Unauthorized" }); + } } export default withMiddleware("HTTP_GET_DELETE_PATCH")( diff --git a/pages/api/destination-calendars/[id].ts b/pages/api/destination-calendars/[id].ts index 579ba83482..2f643d4120 100644 --- a/pages/api/destination-calendars/[id].ts +++ b/pages/api/destination-calendars/[id].ts @@ -101,7 +101,8 @@ export async function destionationCalendarById( 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)) { + if (userDestinationCalendars.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { switch (method) { case "GET": await prisma.destinationCalendar @@ -154,7 +155,7 @@ export async function destionationCalendarById( res.status(405).json({ message: "Method not allowed" }); break; } - } else res.status(401).json({ message: "Unauthorized" }); + } } export default withMiddleware("HTTP_GET_DELETE_PATCH")( diff --git a/pages/api/event-type-custom-inputs/[id].ts b/pages/api/event-type-custom-inputs/[id].ts index 5ff11ff884..4df7114cef 100644 --- a/pages/api/event-type-custom-inputs/[id].ts +++ b/pages/api/event-type-custom-inputs/[id].ts @@ -102,7 +102,9 @@ async function eventTypeById(req: NextApiRequest, res: NextApiResponse eventTypeCustomInput.id ); - if (userEventTypeCustomInputIds.includes(safeQuery.data.id)) { + if (!userEventTypeCustomInputIds.includes(safeQuery.data.id)) + res.status(401).json({ message: "Unauthorized" }); + else { switch (method) { case "GET": await prisma.eventTypeCustomInput @@ -155,7 +157,7 @@ async function eventTypeById(req: NextApiRequest, res: NextApiResponse eventType.id); - if (userEventTypes.includes(safeQuery.data.id)) { + if (!userEventTypes.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { switch (method) { case "GET": await prisma.eventType diff --git a/pages/api/memberships/[id].ts b/pages/api/memberships/[id].ts index 4c90122f70..acb8f03c0c 100644 --- a/pages/api/memberships/[id].ts +++ b/pages/api/memberships/[id].ts @@ -108,7 +108,8 @@ export async function membershipById(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/schedules/[id].ts b/pages/api/schedules/[id].ts index e0b83f106b..a8fa501412 100644 --- a/pages/api/schedules/[id].ts +++ b/pages/api/schedules/[id].ts @@ -93,7 +93,8 @@ export async function scheduleById(req: NextApiRequest, res: NextApiResponse schedule.id); - if (userScheduleIds.includes(safeQuery.data.id)) { + if (!userScheduleIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { switch (method) { case "GET": await prisma.schedule @@ -144,7 +145,7 @@ export async function scheduleById(req: NextApiRequest, res: NextApiResponse membership.teamId); - if (userTeamIds.includes(safeQuery.data.id)) { + if (!userTeamIds.includes(safeQuery.data.id)) res.status(401).json({ message: "Unauthorized" }); + else { switch (method) { case "GET": await prisma.team @@ -148,7 +149,7 @@ export async function teamById(req: NextApiRequest, res: NextApiResponse Date: Sat, 23 Apr 2022 02:22:43 +0200 Subject: [PATCH 23/24] fix: remove comments --- pages/api/event-type-custom-inputs/index.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/pages/api/event-type-custom-inputs/index.ts b/pages/api/event-type-custom-inputs/index.ts index 82c23f8593..5b3b249ab4 100644 --- a/pages/api/event-type-custom-inputs/index.ts +++ b/pages/api/event-type-custom-inputs/index.ts @@ -48,12 +48,7 @@ async function createOrlistAllEventTypeCustomInputs( const userId = req.userId; const data = await prisma.eventType.findMany({ where: { userId } }); const userEventTypes = data.map((eventType) => eventType.id); - // const userEventTypeCustomInputs = await prisma.eventTypeCustomInput.findMany({ - // where: { eventType: userEventTypes }, - // }); - // const userEventTypeCustomInputIds = userEventTypeCustomInputs.map( - // (eventTypeCustomInput) => eventTypeCustomInput.id - // ); + if (method === "GET") { const data = await prisma.eventTypeCustomInput.findMany({ where: { eventType: userEventTypes } }); const event_type_custom_inputs = data.map((eventTypeCustomInput) => From 4e8fae7391a25fe188a5ba8e9fcbee0dfdfb4ad1 Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Sat, 23 Apr 2022 02:26:35 +0200 Subject: [PATCH 24/24] rename apiKey --- lib/helpers/verifyApiKey.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/helpers/verifyApiKey.ts b/lib/helpers/verifyApiKey.ts index 6a8c24df4e..ab8115faab 100644 --- a/lib/helpers/verifyApiKey.ts +++ b/lib/helpers/verifyApiKey.ts @@ -11,7 +11,7 @@ declare module "next" { } } -// Used to check if the API key is not expired, could be extracted if reused. but not for now. +// 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)) { @@ -19,9 +19,9 @@ export const dateNotInPast = function (date: Date) { } }; -// 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) return 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. @@ -29,11 +29,11 @@ export const verifyApiKey: NextMiddleware = async (req, res, next) => { // Check if the hashed api key exists in database. 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 api key is not valid" }); + 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 api key is expired" }); + return res.status(401).json({ error: "This apiKey is expired" }); } - if (!apiKey.userId) return res.status(404).json({ error: "No user found for this api key" }); + 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();