diff --git a/lib/helpers/verifyApiKey.ts b/lib/helpers/verifyApiKey.ts index 55ee111451..740c4a2de4 100644 --- a/lib/helpers/verifyApiKey.ts +++ b/lib/helpers/verifyApiKey.ts @@ -17,8 +17,10 @@ export const verifyApiKey: NextMiddleware = async (req, res, next) => { res.status(401).json({ error: "Your api key is not valid" }); throw new Error("No api key found"); } + if (apiKey.userId) { + res.setHeader("X-Calcom-User-ID", apiKey.userId); + } if (apiKey.expiresAt && apiKey.userId && dateInPast(today, apiKey.expiresAt)) { - res.setHeader("Calcom-User-ID", apiKey.userId); await next(); } else res.status(401).json({ error: "Your api key is not valid" }); }; diff --git a/lib/utils/getUserFromHeader.ts b/lib/utils/getUserFromHeader.ts new file mode 100644 index 0000000000..fc2e524954 --- /dev/null +++ b/lib/utils/getUserFromHeader.ts @@ -0,0 +1,3 @@ +import { NextApiResponse } from "next"; + +export const getCalcomUserId = (res: NextApiResponse) => res.getHeader("x-calcom-user-id") as number; diff --git a/lib/validations/shared/baseApiParams.ts b/lib/validations/shared/baseApiParams.ts index a7791a5b9d..b670be62d3 100644 --- a/lib/validations/shared/baseApiParams.ts +++ b/lib/validations/shared/baseApiParams.ts @@ -6,7 +6,7 @@ export const baseApiParams = z .object({ // since we added apiKey as query param this is required by next-validations helper // for query params to work properly and not fail. - apiKey: z.string().cuid().optional(), + apiKey: z.string().optional(), // version required for supporting /v1/ redirect to query in api as *?version=1 version: z.string().optional(), }) diff --git a/templates/newIndex.ts b/pages/api/reminder-mails/newIndex.ts similarity index 100% rename from templates/newIndex.ts rename to pages/api/reminder-mails/newIndex.ts diff --git a/pages/api/schedules/newIndex.ts b/pages/api/schedules/newIndex.ts new file mode 100644 index 0000000000..732eb013b2 --- /dev/null +++ b/pages/api/schedules/newIndex.ts @@ -0,0 +1,68 @@ +import type { NextApiRequest, NextApiResponse } from "next"; + +import prisma from "@calcom/prisma"; + +import { withMiddleware } from "@lib/helpers/withMiddleware"; +import { PaymentResponse, PaymentsResponse } from "@lib/types"; +import { schemaPaymentBodyParams, schemaPaymentPublic, withValidPayment } from "@lib/validations/payment"; + +/** + * @swagger + * /api/payments: + * get: + * summary: Get all payments + * tags: + * - payments + * responses: + * 200: + * description: OK + * 401: + * description: Authorization information is missing or invalid. + * 404: + * description: No payments were found + * post: + * summary: Creates a new payment + * tags: + * - payments + * responses: + * 201: + * description: OK, payment created + * model: Payment + * 400: + * description: Bad request. Payment body is invalid. + * 401: + * description: Authorization information is missing or invalid. + */ +async function createOrlistAllPayments( + req: NextApiRequest, + res: NextApiResponse +) { + const { method } = req; + if (method === "GET") { + const payments = await prisma.payment.findMany(); + const data = payments.map((payment) => schemaPaymentPublic.parse(payment)); + if (data) res.status(200).json({ data }); + else + (error: Error) => + res.status(404).json({ + message: "No Payments were found", + error, + }); + } else if (method === "POST") { + const safe = schemaPaymentBodyParams.safeParse(req.body); + if (!safe.success) throw new Error("Invalid request body"); + + const payment = await prisma.payment.create({ data: safe.data }); + const data = schemaPaymentPublic.parse(payment); + + if (data) res.status(201).json({ data, message: "Payment created successfully" }); + else + (error: Error) => + res.status(400).json({ + message: "Could not create new payment", + error, + }); + } else res.status(405).json({ message: `Method ${method} not allowed` }); +} + +export default withMiddleware("HTTP_GET_OR_POST")(withValidPayment(createOrlistAllPayments)); diff --git a/pages/api/selected-calendars/newIndex.ts b/pages/api/selected-calendars/newIndex.ts new file mode 100644 index 0000000000..732eb013b2 --- /dev/null +++ b/pages/api/selected-calendars/newIndex.ts @@ -0,0 +1,68 @@ +import type { NextApiRequest, NextApiResponse } from "next"; + +import prisma from "@calcom/prisma"; + +import { withMiddleware } from "@lib/helpers/withMiddleware"; +import { PaymentResponse, PaymentsResponse } from "@lib/types"; +import { schemaPaymentBodyParams, schemaPaymentPublic, withValidPayment } from "@lib/validations/payment"; + +/** + * @swagger + * /api/payments: + * get: + * summary: Get all payments + * tags: + * - payments + * responses: + * 200: + * description: OK + * 401: + * description: Authorization information is missing or invalid. + * 404: + * description: No payments were found + * post: + * summary: Creates a new payment + * tags: + * - payments + * responses: + * 201: + * description: OK, payment created + * model: Payment + * 400: + * description: Bad request. Payment body is invalid. + * 401: + * description: Authorization information is missing or invalid. + */ +async function createOrlistAllPayments( + req: NextApiRequest, + res: NextApiResponse +) { + const { method } = req; + if (method === "GET") { + const payments = await prisma.payment.findMany(); + const data = payments.map((payment) => schemaPaymentPublic.parse(payment)); + if (data) res.status(200).json({ data }); + else + (error: Error) => + res.status(404).json({ + message: "No Payments were found", + error, + }); + } else if (method === "POST") { + const safe = schemaPaymentBodyParams.safeParse(req.body); + if (!safe.success) throw new Error("Invalid request body"); + + const payment = await prisma.payment.create({ data: safe.data }); + const data = schemaPaymentPublic.parse(payment); + + if (data) res.status(201).json({ data, message: "Payment created successfully" }); + else + (error: Error) => + res.status(400).json({ + message: "Could not create new payment", + error, + }); + } else res.status(405).json({ message: `Method ${method} not allowed` }); +} + +export default withMiddleware("HTTP_GET_OR_POST")(withValidPayment(createOrlistAllPayments)); diff --git a/pages/api/users/[id].ts b/pages/api/users/[id].ts index fa0b4c7255..e309288253 100644 --- a/pages/api/users/[id].ts +++ b/pages/api/users/[id].ts @@ -4,6 +4,7 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import type { UserResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getUserFromHeader"; import { schemaQueryIdParseInt, withValidQueryIdTransformParseInt, @@ -14,7 +15,7 @@ import { schemaUserBodyParams, schemaUserPublic } from "@lib/validations/user"; * @swagger * /api/users/{id}: * get: - * summary: Get a user by ID + * summary: Get a user by ID, returns your user if regular user. * parameters: * - in: path * name: id @@ -84,47 +85,49 @@ export async function userById(req: NextApiRequest, res: NextApiResponse schemaUserPublic.parse(user)) + .then((data) => res.status(200).json({ data })) + .catch((error: Error) => + res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error }) + ); + break; - switch (method) { - case "GET": - await prisma.user - .findUnique({ where: { id: safeQuery.data.id } }) - .then((user) => schemaUserPublic.parse(user)) - .then((data) => res.status(200).json({ data })) - .catch((error: Error) => - res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "PATCH": + if (!safeBody.success) throw new Error("Invalid request body"); + await prisma.user + .update({ + where: { id: safeQuery.data.id }, + data: safeBody.data, + }) + .then((user) => schemaUserPublic.parse(user)) + .then((data) => res.status(200).json({ data })) + .catch((error: Error) => + res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error }) + ); + break; - case "PATCH": - if (!safeBody.success) throw new Error("Invalid request body"); - await prisma.user - .update({ - where: { id: safeQuery.data.id }, - data: safeBody.data, - }) - .then((user) => schemaUserPublic.parse(user)) - .then((data) => res.status(200).json({ data })) - .catch((error: Error) => - res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error }) - ); - break; + case "DELETE": + await prisma.user + .delete({ where: { id: safeQuery.data.id } }) + .then(() => + res.status(200).json({ message: `User with id: ${safeQuery.data.id} deleted successfully` }) + ) + .catch((error: Error) => + res.status(404).json({ message: `User with id: ${safeQuery.data.id} not found`, error }) + ); + break; - case "DELETE": - await prisma.user - .delete({ where: { id: safeQuery.data.id } }) - .then(() => - res.status(200).json({ message: `User with id: ${safeQuery.data.id} deleted successfully` }) - ) - .catch((error: Error) => - res.status(404).json({ message: `User 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(userById)); diff --git a/pages/api/users/index.ts b/pages/api/users/index.ts index 6bb3763a88..23ec86eba0 100644 --- a/pages/api/users/index.ts +++ b/pages/api/users/index.ts @@ -4,13 +4,14 @@ import prisma from "@calcom/prisma"; import { withMiddleware } from "@lib/helpers/withMiddleware"; import { UsersResponse } from "@lib/types"; +import { getCalcomUserId } from "@lib/utils/getUserFromHeader"; import { schemaUserPublic } from "@lib/validations/user"; /** * @swagger * /api/users: * get: - * summary: Get all users + * summary: Get all users (admin only), returns your user if regular user. * tags: * - users * responses: @@ -21,10 +22,14 @@ import { schemaUserPublic } from "@lib/validations/user"; * 404: * description: No users were found */ -async function allUsers(_: NextApiRequest, res: NextApiResponse) { - const users = await prisma.user.findMany(); +async function allUsers(req: NextApiRequest, res: NextApiResponse) { + const userId = getCalcomUserId(res); + const users = await prisma.user.findMany({ + where: { + id: userId, + }, + }); const data = users.map((user) => schemaUserPublic.parse(user)); - if (data) res.status(200).json({ data }); else (error: Error) => @@ -33,5 +38,6 @@ async function allUsers(_: NextApiRequest, res: NextApiResponse) error, }); } +// No POST endpoint for users for now as a regular user you're expected to signup. export default withMiddleware("HTTP_GET")(allUsers); diff --git a/pages/api/users/new.ts b/pages/api/users/new.ts deleted file mode 100644 index df3310c09c..0000000000 --- a/pages/api/users/new.ts +++ /dev/null @@ -1,51 +0,0 @@ -import type { NextApiRequest, NextApiResponse } from "next"; - -import prisma from "@calcom/prisma"; - -import { withMiddleware } from "@lib/helpers/withMiddleware"; -import type { UserResponse } from "@lib/types"; -import { schemaUserBodyParams, schemaUserPublic, withValidUser } from "@lib/validations/user"; - -/** - * @swagger - * /api/users/new: - * post: - * summary: Add a new user - * consumes: - * - application/json - * parameters: - * - in: body - * name: user - * description: The user to edit - * schema: - * type: object - * $ref: '#/components/schemas/User' - * required: true - * tags: - * - users - * responses: - * 201: - * description: OK, user created - * model: User - * 400: - * description: Bad request. User body is invalid. - * 401: - * description: Authorization information is missing or invalid. - */ -async function createUser(req: NextApiRequest, res: NextApiResponse) { - const safe = schemaUserBodyParams.safeParse(req.body); - if (!safe.success) throw new Error("Invalid request body", safe.error); - - const user = await prisma.user.create({ data: safe.data }); - const data = schemaUserPublic.parse(user); - - if (data) res.status(201).json({ data, message: "User created successfully" }); - else - (error: Error) => - res.status(400).json({ - message: "Could not create new user", - error, - }); -} - -export default withMiddleware("HTTP_POST")(withValidUser(createUser)); diff --git a/templates/endpoints/newIndex.ts b/templates/endpoints/newIndex.ts new file mode 100644 index 0000000000..732eb013b2 --- /dev/null +++ b/templates/endpoints/newIndex.ts @@ -0,0 +1,68 @@ +import type { NextApiRequest, NextApiResponse } from "next"; + +import prisma from "@calcom/prisma"; + +import { withMiddleware } from "@lib/helpers/withMiddleware"; +import { PaymentResponse, PaymentsResponse } from "@lib/types"; +import { schemaPaymentBodyParams, schemaPaymentPublic, withValidPayment } from "@lib/validations/payment"; + +/** + * @swagger + * /api/payments: + * get: + * summary: Get all payments + * tags: + * - payments + * responses: + * 200: + * description: OK + * 401: + * description: Authorization information is missing or invalid. + * 404: + * description: No payments were found + * post: + * summary: Creates a new payment + * tags: + * - payments + * responses: + * 201: + * description: OK, payment created + * model: Payment + * 400: + * description: Bad request. Payment body is invalid. + * 401: + * description: Authorization information is missing or invalid. + */ +async function createOrlistAllPayments( + req: NextApiRequest, + res: NextApiResponse +) { + const { method } = req; + if (method === "GET") { + const payments = await prisma.payment.findMany(); + const data = payments.map((payment) => schemaPaymentPublic.parse(payment)); + if (data) res.status(200).json({ data }); + else + (error: Error) => + res.status(404).json({ + message: "No Payments were found", + error, + }); + } else if (method === "POST") { + const safe = schemaPaymentBodyParams.safeParse(req.body); + if (!safe.success) throw new Error("Invalid request body"); + + const payment = await prisma.payment.create({ data: safe.data }); + const data = schemaPaymentPublic.parse(payment); + + if (data) res.status(201).json({ data, message: "Payment created successfully" }); + else + (error: Error) => + res.status(400).json({ + message: "Could not create new payment", + error, + }); + } else res.status(405).json({ message: `Method ${method} not allowed` }); +} + +export default withMiddleware("HTTP_GET_OR_POST")(withValidPayment(createOrlistAllPayments));