2022-07-08 17:21:40 +00:00
|
|
|
import type { NextApiRequest } from "next";
|
|
|
|
|
|
|
|
import { HttpError } from "@calcom/lib/http-error";
|
|
|
|
|
2022-11-25 13:56:58 +00:00
|
|
|
import { schemaQueryIdParseInt } from "~/lib/validations/shared/queryIdTransformParseInt";
|
2022-07-08 17:21:40 +00:00
|
|
|
|
2022-10-11 01:46:45 +00:00
|
|
|
async function authMiddleware(req: NextApiRequest) {
|
2022-07-08 17:21:40 +00:00
|
|
|
const { userId, prisma, isAdmin, query } = req;
|
|
|
|
const { id } = schemaQueryIdParseInt.parse(query);
|
|
|
|
const userWithBookings = await prisma.user.findUnique({
|
|
|
|
where: { id: userId },
|
|
|
|
include: { bookings: true },
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!userWithBookings) throw new HttpError({ statusCode: 404, message: "User not found" });
|
|
|
|
|
|
|
|
const userBookingIds = userWithBookings.bookings.map((booking) => booking.id);
|
|
|
|
|
|
|
|
if (!isAdmin && !userBookingIds.includes(id)) {
|
|
|
|
throw new HttpError({ statusCode: 401, message: "You are not authorized" });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-11 01:46:45 +00:00
|
|
|
export default authMiddleware;
|