Add userId check in users getAll and id endpoints

This commit is contained in:
Agusti Fernandez Pardo committed 2022-04-07 21:55:43 +02:00
1 parent fc2978a61b
commit 325b19ba3f
10 files changed
+263 -96

No files matched your search

+3 -1
View File
@@ -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" });
};
+3
View File
@@ -0,0 +1,3 @@
import { NextApiResponse } from "next";
export const getCalcomUserId = (res: NextApiResponse) => res.getHeader("x-calcom-user-id") as number;
+1 -1
View File
@@ -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(),
})
File renamed without changes.
+68
View File
@@ -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<PaymentsResponse | PaymentResponse>
) {
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));
+68
View File
@@ -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<PaymentsResponse | PaymentResponse>
) {
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));
+42 -39
View File
@@ -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<UserRes
const safeQuery = await schemaQueryIdParseInt.safeParse(query);
const safeBody = await schemaUserBodyParams.safeParse(body);
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
const userId = getCalcomUserId(res);
if (safeQuery.data.id === userId) {
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;
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));
+10 -4
View File
@@ -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<UsersResponse>) {
const users = await prisma.user.findMany();
async function allUsers(req: NextApiRequest, res: NextApiResponse<UsersResponse>) {
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<UsersResponse>)
error,
});
}
// No POST endpoint for users for now as a regular user you're expected to signup.
export default withMiddleware("HTTP_GET")(allUsers);
-51
View File
@@ -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<UserResponse>) {
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));
+68
View File
@@ -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<PaymentsResponse | PaymentResponse>
) {
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));