feat: credentials, teams

This commit is contained in:
Agusti Fernandez Pardo committed 2022-04-13 02:12:16 +02:00
1 parent 9447bd859d
commit d987d52dbb
8 files changed
+85 -55

No files matched your search

+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) => { export const verifyApiKey: NextMiddleware = async (req, res, next) => {
if (!req.query.apiKey) res.status(401).json({ message: "No API key provided" }); 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); const hashedKey = hashAPIKey(strippedApiKey);
await prisma.apiKey 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" }); res.status(401).json({ error: "You did not provide an api key" });
throw new Error("No api key found"); 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(); if (apiKey.expiresAt && apiKey.userId && dateInPast(today, apiKey.expiresAt)) await next();
}) })
.catch((error) => { .catch((error) => {
-1
View File
@@ -61,7 +61,6 @@ async function createOrlistAllAttendees(
} else if (method === "POST") { } else if (method === "POST") {
const safe = schemaAttendeeBodyParams.safeParse(req.body); const safe = schemaAttendeeBodyParams.safeParse(req.body);
if (!safe.success) { if (!safe.success) {
console.log(safe.error);
throw new Error("Invalid request body", safe.error); throw new Error("Invalid request body", safe.error);
} }
const bookingId = safe.data.bookingId; const bookingId = safe.data.bookingId;
+28 -10
View File
@@ -49,7 +49,6 @@ async function createOrlistAllBookingReferences(
}); });
if (!userWithBookings) throw new Error("User not found"); if (!userWithBookings) throw new Error("User not found");
const userBookingIds = userWithBookings.bookings.map((booking: any) => booking.id).flat(); const userBookingIds = userWithBookings.bookings.map((booking: any) => booking.id).flat();
console.log(userBookingIds);
if (method === "GET") { if (method === "GET") {
const data = await prisma.bookingReference.findMany({ where: { id: { in: userBookingIds } } }); const data = await prisma.bookingReference.findMany({ where: { id: { in: userBookingIds } } });
const booking_references = data.map((bookingReference) => const booking_references = data.map((bookingReference) =>
@@ -64,18 +63,37 @@ async function createOrlistAllBookingReferences(
}); });
} else if (method === "POST") { } else if (method === "POST") {
const safe = schemaBookingReferenceBodyParams.safeParse(req.body); 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); const booking_reference = schemaBookingReferencePublic.parse(data);
const userId = await getCalcomUserId(res);
if (data) res.status(201).json({ booking_reference, message: "BookingReference created successfully" }); const userWithBookings = await prisma.user.findUnique({
else where: { id: userId },
(error: Error) => include: { bookings: true },
res.status(400).json({ });
message: "Could not create new booking reference", if (!userWithBookings) {
error, 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` }); } 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 { withMiddleware } from "@lib/helpers/withMiddleware";
import type { CredentialResponse } from "@lib/types"; import type { CredentialResponse } from "@lib/types";
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
import { schemaCredentialBodyParams, schemaCredentialPublic } from "@lib/validations/credential"; import { schemaCredentialBodyParams, schemaCredentialPublic } from "@lib/validations/credential";
import { import {
schemaQueryIdParseInt, schemaQueryIdParseInt,
@@ -84,47 +85,52 @@ export async function credentialById(req: NextApiRequest, res: NextApiResponse<C
const safeQuery = schemaQueryIdParseInt.safeParse(query); const safeQuery = schemaQueryIdParseInt.safeParse(query);
const safeBody = schemaCredentialBodyParams.safeParse(body); const safeBody = schemaCredentialBodyParams.safeParse(body);
if (!safeQuery.success) throw new Error("Invalid request query", safeQuery.error); 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 "PATCH":
case "GET": if (!safeBody.success) throw new Error("Invalid request body");
await prisma.credential await prisma.credential
.findUnique({ where: { id: safeQuery.data.id } }) .update({
.then((data) => schemaCredentialPublic.parse(data)) where: { id: safeQuery.data.id },
.then((credential) => res.status(200).json({ credential })) data: safeBody.data,
.catch((error: Error) => })
res.status(404).json({ message: `Credential with id: ${safeQuery.data.id} not found`, error }) .then((data) => schemaCredentialPublic.parse(data))
); .then((credential) => res.status(200).json({ credential }))
break; .catch((error: Error) =>
res.status(404).json({ message: `Credential with id: ${safeQuery.data.id} not found`, error })
);
break;
case "PATCH": case "DELETE":
if (!safeBody.success) throw new Error("Invalid request body"); await prisma.credential
await prisma.credential .delete({ where: { id: safeQuery.data.id } })
.update({ .then(() =>
where: { id: safeQuery.data.id }, res.status(200).json({ message: `Credential with id: ${safeQuery.data.id} deleted successfully` })
data: safeBody.data, )
}) .catch((error: Error) =>
.then((data) => schemaCredentialPublic.parse(data)) res.status(404).json({ message: `Credential with id: ${safeQuery.data.id} not found`, error })
.then((credential) => res.status(200).json({ credential })) );
.catch((error: Error) => break;
res.status(404).json({ message: `Credential with id: ${safeQuery.data.id} not found`, error })
);
break;
case "DELETE": default:
await prisma.credential res.status(405).json({ message: "Method not allowed" });
.delete({ where: { id: safeQuery.data.id } }) break;
.then(() => }
res.status(200).json({ message: `Credential with id: ${safeQuery.data.id} deleted successfully` }) } else res.status(401).json({ message: "Unauthorized" });
)
.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;
}
} }
export default withMiddleware("HTTP_GET_DELETE_PATCH")(withValidQueryIdTransformParseInt(credentialById)); 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 { withMiddleware } from "@lib/helpers/withMiddleware";
import { CredentialResponse, CredentialsResponse } from "@lib/types"; import { CredentialResponse, CredentialsResponse } from "@lib/types";
import { getCalcomUserId } from "@lib/utils/getCalcomUserId";
import { schemaCredentialBodyParams, schemaCredentialPublic } from "@lib/validations/credential"; import { schemaCredentialBodyParams, schemaCredentialPublic } from "@lib/validations/credential";
/** /**
@@ -38,8 +39,10 @@ async function createOrlistAllCredentials(
res: NextApiResponse<CredentialsResponse | CredentialResponse> res: NextApiResponse<CredentialsResponse | CredentialResponse>
) { ) {
const { method } = req; const { method } = req;
const userId = getCalcomUserId(res);
if (method === "GET") { 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)); const credentials = data.map((credential) => schemaCredentialPublic.parse(credential));
if (credentials) res.status(200).json({ credentials }); if (credentials) res.status(200).json({ credentials });
else else
@@ -55,7 +58,10 @@ async function createOrlistAllCredentials(
const data = await prisma.credential.create({ data: safe.data }); const data = await prisma.credential.create({ data: safe.data });
const credential = schemaCredentialPublic.parse(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 else
(error: Error) => (error: Error) =>
res.status(400).json({ 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({ const userWithMemberships = await prisma.membership.findMany({
where: { userId: userId }, where: { userId: userId },
}); });
//FIXME: This is a hack to get the teamId from the user's membership
console.log(userWithMemberships); console.log(userWithMemberships);
switch (method) { switch (method) {
case "GET": 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"); if (!safe.success) throw new Error("Invalid request body");
const team = await prisma.team.create({ data: safe.data }); const team = await prisma.team.create({ data: safe.data });
const membership = await prisma.membership.create({ const membership = await prisma.membership.create({
data: { userId: userId, teamId: team.id, role: "ADMIN" }, data: { userId, teamId: team.id, role: "ADMIN" },
}); });
console.log(membership); console.log(membership);
const data = schemaTeamPublic.parse(team); const data = schemaTeamPublic.parse(team);