feat: credentials, teams

This commit is contained in:
Agusti Fernandez Pardo
2022-04-13 02:12:16 +02:00
parent 9447bd859d
commit d987d52dbb
8 changed files with 85 additions and 55 deletions
+1 -1
View File
@@ -1 +1 @@
API_KEY_PREFIX=cal_
API_KEY_PREFIX=pt_secret_
+2 -2
View File
@@ -15,7 +15,7 @@ const today = new Date();
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
if (!req.query.apiKey) res.status(401).json({ message: "No API key provided" });
const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "cal_", "");
const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "pt_secret_", "");
const hashedKey = hashAPIKey(strippedApiKey);
await prisma.apiKey
@@ -25,7 +25,7 @@ export const verifyApiKey: NextMiddleware = async (req, res, next) => {
res.status(401).json({ error: "You did not provide an api key" });
throw new Error("No api key found");
}
if (apiKey.userId) res.setHeader("X-Calcom-User-ID", apiKey?.userId);
if (apiKey.userId) res.setHeader("X-Calcom-User-ID", apiKey.userId);
if (apiKey.expiresAt && apiKey.userId && dateInPast(today, apiKey.expiresAt)) await next();
})
.catch((error) => {
-1
View File
@@ -61,7 +61,6 @@ async function createOrlistAllAttendees(
} else if (method === "POST") {
const safe = schemaAttendeeBodyParams.safeParse(req.body);
if (!safe.success) {
console.log(safe.error);
throw new Error("Invalid request body", safe.error);
}
const bookingId = safe.data.bookingId;
+28 -10
View File
@@ -49,7 +49,6 @@ async function createOrlistAllBookingReferences(
});
if (!userWithBookings) throw new Error("User not found");
const userBookingIds = userWithBookings.bookings.map((booking: any) => booking.id).flat();
console.log(userBookingIds);
if (method === "GET") {
const data = await prisma.bookingReference.findMany({ where: { id: { in: userBookingIds } } });
const booking_references = data.map((bookingReference) =>
@@ -64,18 +63,37 @@ async function createOrlistAllBookingReferences(
});
} else if (method === "POST") {
const safe = schemaBookingReferenceBodyParams.safeParse(req.body);
if (!safe.success) throw new Error("Invalid request body");
if (!safe.success) {
throw new Error("Invalid request body");
}
const data = await prisma.bookingReference.create({ data: safe.data });
const data = await prisma.bookingReference.create({
data: { ...safe.data },
});
const booking_reference = schemaBookingReferencePublic.parse(data);
if (data) res.status(201).json({ booking_reference, message: "BookingReference created successfully" });
else
(error: Error) =>
res.status(400).json({
message: "Could not create new booking reference",
error,
const userId = await getCalcomUserId(res);
const userWithBookings = await prisma.user.findUnique({
where: { id: userId },
include: { bookings: true },
});
if (!userWithBookings) {
throw new Error("User not found");
}
const userBookingIds = userWithBookings.bookings.map((booking: any) => booking.id).flat();
if (userBookingIds.includes(safe.data.bookingId)) {
if (data) {
res.status(201).json({
booking_reference,
message: "BookingReference created successfully",
});
} else {
(error: Error) =>
res.status(400).json({
message: "Could not create new booking reference",
error,
});
}
} else res.status(401).json({ message: "Unauthorized" });
} else res.status(405).json({ message: `Method ${method} not allowed` });
}
+44 -38
View File
@@ -4,6 +4,7 @@ import prisma from "@calcom/prisma";
import { withMiddleware } from "@lib/helpers/withMiddleware";
import type { CredentialResponse } from "@lib/types";
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
import { schemaCredentialBodyParams, schemaCredentialPublic } from "@lib/validations/credential";
import {
schemaQueryIdParseInt,
@@ -84,47 +85,52 @@ export async function credentialById(req: NextApiRequest, res: NextApiResponse<C
const safeQuery = schemaQueryIdParseInt.safeParse(query);
const safeBody = schemaCredentialBodyParams.safeParse(body);
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error);
const userId = getCalcomUserId(res);
const data = await prisma.credential.findMany({ where: { userId } });
const credentialIds = data.map((credential) => credential.id);
// res.status(200).json({ data });
if (credentialIds.includes(safeQuery.data.id)) {
switch (method) {
case "GET":
await prisma.credential
.findUnique({ where: { id: safeQuery.data.id } })
.then((data) => schemaCredentialPublic.parse(data))
.then((credential) => res.status(200).json({ credential }))
.catch((error: Error) =>
res.status(404).json({ message: `Credential with id: ${safeQuery.data.id} not found`, error })
);
break;
switch (method) {
case "GET":
await prisma.credential
.findUnique({ where: { id: safeQuery.data.id } })
.then((data) => schemaCredentialPublic.parse(data))
.then((credential) => res.status(200).json({ credential }))
.catch((error: Error) =>
res.status(404).json({ message: `Credential with id: ${safeQuery.data.id} not found`, error })
);
break;
case "PATCH":
if (!safeBody.success) throw new Error("Invalid request body");
await prisma.credential
.update({
where: { id: safeQuery.data.id },
data: safeBody.data,
})
.then((data) => schemaCredentialPublic.parse(data))
.then((credential) => res.status(200).json({ credential }))
.catch((error: Error) =>
res.status(404).json({ message: `Credential with id: ${safeQuery.data.id} not found`, error })
);
break;
case "PATCH":
if (!safeBody.success) throw new Error("Invalid request body");
await prisma.credential
.update({
where: { id: safeQuery.data.id },
data: safeBody.data,
})
.then((data) => schemaCredentialPublic.parse(data))
.then((credential) => res.status(200).json({ credential }))
.catch((error: Error) =>
res.status(404).json({ message: `Credential with id: ${safeQuery.data.id} not found`, error })
);
break;
case "DELETE":
await prisma.credential
.delete({ where: { id: safeQuery.data.id } })
.then(() =>
res.status(200).json({ message: `Credential with id: ${safeQuery.data.id} deleted successfully` })
)
.catch((error: Error) =>
res.status(404).json({ message: `Credential with id: ${safeQuery.data.id} not found`, error })
);
break;
case "DELETE":
await prisma.credential
.delete({ where: { id: safeQuery.data.id } })
.then(() =>
res.status(200).json({ message: `Credential with id: ${safeQuery.data.id} deleted successfully` })
)
.catch((error: Error) =>
res.status(404).json({ message: `Credential 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(credentialById));
+8 -2
View File
@@ -4,6 +4,7 @@ import prisma from "@calcom/prisma";
import { withMiddleware } from "@lib/helpers/withMiddleware";
import { CredentialResponse, CredentialsResponse } from "@lib/types";
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
import { schemaCredentialBodyParams, schemaCredentialPublic } from "@lib/validations/credential";
/**
@@ -38,8 +39,10 @@ async function createOrlistAllCredentials(
res: NextApiResponse<CredentialsResponse | CredentialResponse>
) {
const { method } = req;
const userId = getCalcomUserId(res);
if (method === "GET") {
const data = await prisma.credential.findMany();
const data = await prisma.credential.findMany({ where: { userId } });
const credentials = data.map((credential) => schemaCredentialPublic.parse(credential));
if (credentials) res.status(200).json({ credentials });
else
@@ -55,7 +58,10 @@ async function createOrlistAllCredentials(
const data = await prisma.credential.create({ data: safe.data });
const credential = schemaCredentialPublic.parse(data);
if (credential) res.status(201).json({ credential, message: "Credential created successfully" });
if (credential)
res
.status(201)
.json({ credential: { ...credential, userId }, message: "Credential created successfully" });
else
(error: Error) =>
res.status(400).json({
+1
View File
@@ -89,6 +89,7 @@ export async function teamById(req: NextApiRequest, res: NextApiResponse<TeamRes
const userWithMemberships = await prisma.membership.findMany({
where: { userId: userId },
});
//FIXME: This is a hack to get the teamId from the user's membership
console.log(userWithMemberships);
switch (method) {
case "GET":
+1 -1
View File
@@ -56,7 +56,7 @@ async function createOrlistAllTeams(req: NextApiRequest, res: NextApiResponse<Te
if (!safe.success) throw new Error("Invalid request body");
const team = await prisma.team.create({ data: safe.data });
const membership = await prisma.membership.create({
data: { userId: userId, teamId: team.id, role: "ADMIN" },
data: { userId, teamId: team.id, role: "ADMIN" },
});
console.log(membership);
const data = schemaTeamPublic.parse(team);