fix: merge w main

This commit is contained in:
Agusti Fernandez Pardo committed 2022-06-18 01:52:37 +02:00
commit 6e68671c2a
33 files changed
+676 -399

No files matched your search

+3 -1
View File
@@ -1,7 +1,7 @@
import type { IncomingMessage } from "http";
import { NextMiddleware } from "next-api-middleware";
import type { PrismaClient } from ".prisma/client";
import type { PrismaClient } from "@calcom/prisma/client";
/** @todo figure how to use the one from `@calcom/types` */
/** @todo: remove once `@calcom/types` is updated with it.*/
@@ -14,8 +14,10 @@ declare module "next" {
prisma: PrismaClient;
session: { user: { id: number } };
query: { [key: string]: string | string[] };
isAdmin: boolean;
}
}
export const extendRequest: NextMiddleware = async (req, res, next) => {
// @note: just an empty middleware, we care about extending the next api request types only.
await next();
};
+5 -4
View File
@@ -1,8 +1,9 @@
// import type { IncomingMessage } from "http";
import { NextMiddleware } from "next-api-middleware";
import { hashAPIKey } from "@calcom/ee/lib/api/apiKeys";
import { isAdminGuard } from "@lib/utils/isAdmin";
// Used to check if the apiKey is not expired, could be extracted if reused. but not for now.
export const dateNotInPast = function (date: Date) {
const now = new Date();
@@ -15,15 +16,12 @@ export const dateNotInPast = function (date: Date) {
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
const { prisma } = req;
if (!req.query.apiKey) return res.status(401).json({ message: "No apiKey provided" });
console.log("req.query.apiKey", req.query.apiKey);
// We remove the prefix from the user provided api_key. If no env set default to "cal_"
const strippedApiKey = `${req.query.apiKey}`.replace(process.env.API_KEY_PREFIX || "cal_", "");
console.log("strippedApiKey", strippedApiKey);
// Hash the key again before matching against the database records.
const hashedKey = hashAPIKey(strippedApiKey);
console.log("hashedKey", hashedKey);
// Check if the hashed api key exists in database.
const apiKey = await prisma.apiKey.findUnique({ where: { hashedKey } });
// console.log("apiKey", apiKey);
@@ -35,5 +33,8 @@ export const verifyApiKey: NextMiddleware = async (req, res, next) => {
if (!apiKey.userId) return res.status(404).json({ error: "No user found for this apiKey" });
/* We save the user id in the request for later use */
req.userId = apiKey.userId;
/* We save the isAdmin boolean here for later use */
req.isAdmin = await isAdminGuard(req.userId);
await next();
};
+62
View File
@@ -0,0 +1,62 @@
import { TFunction } from "next-i18next";
type EventNameObjectType = {
attendeeName: string;
eventType: string;
eventName?: string | null;
host: string;
location?: string;
t: TFunction;
};
export function getEventName(eventNameObj: EventNameObjectType, forAttendeeView = false) {
if (!eventNameObj.eventName)
return eventNameObj.t("event_between_users", {
eventName: eventNameObj.eventType,
host: eventNameObj.host,
attendeeName: eventNameObj.attendeeName,
});
let eventName = eventNameObj.eventName;
let locationString = "";
if (eventNameObj.eventName.includes("{LOCATION}")) {
switch (eventNameObj.location) {
case "inPerson":
locationString = "In Person";
break;
case "userPhone":
case "phone":
locationString = "Phone";
break;
case "integrations:daily":
locationString = "Cal Video";
break;
case "integrations:zoom":
locationString = "Zoom";
break;
case "integrations:huddle01":
locationString = "Huddle01";
break;
case "integrations:tandem":
locationString = "Tandem";
break;
case "integrations:office365_video":
locationString = "MS Teams";
break;
case "integrations:jitsi":
locationString = "Jitsi";
break;
}
eventName = eventName.replace("{LOCATION}", locationString);
}
return (
eventName
// Need this for compatibility with older event names
.replace("{USER}", eventNameObj.attendeeName)
.replace("{ATTENDEE}", eventNameObj.attendeeName)
.replace("{HOST}", eventNameObj.host)
.replace("{HOST/ATTENDEE}", forAttendeeView ? eventNameObj.host : eventNameObj.attendeeName)
);
}
+78
View File
@@ -0,0 +1,78 @@
import { Webhook } from "@prisma/client";
import { compile } from "handlebars";
// import type { CalendarEvent } from "@calcom/types/Calendar"; Add this to make it strict, change data: any to CalendarEvent type
type ContentType = "application/json" | "application/x-www-form-urlencoded";
function applyTemplate(template: string, data: any, contentType: ContentType) {
const compiled = compile(template)(data);
if (contentType === "application/json") {
return JSON.stringify(jsonParse(compiled));
}
return compiled;
}
function jsonParse(jsonString: string) {
try {
return JSON.parse(jsonString);
} catch (e) {
// don't do anything.
console.error(`error jsonParsing in sendPayload`);
}
return false;
}
const sendPayload = async (
triggerEvent: string,
createdAt: string,
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
data: any & {
metadata?: { [key: string]: string };
rescheduleUid?: string;
bookingId?: number;
}
) => {
const { subscriberUrl, appId, payloadTemplate: template } = webhook;
if (!subscriberUrl || !data) {
throw new Error("Missing required elements to send webhook payload.");
}
const contentType =
!template || jsonParse(template) ? "application/json" : "application/x-www-form-urlencoded";
data.description = data.description || data.additionalNotes;
let body;
/* Zapier id is hardcoded in the DB, we send the raw data for this case */
if (appId === "zapier") {
body = JSON.stringify(data);
} else if (template) {
body = applyTemplate(template, data, contentType);
} else {
body = JSON.stringify({
triggerEvent: triggerEvent,
createdAt: createdAt,
payload: data,
});
}
const response = await fetch(subscriberUrl, {
method: "POST",
headers: {
"Content-Type": contentType,
},
body,
});
const text = await response.text();
return {
ok: response.ok,
status: response.status,
message: text,
};
};
export default sendPayload;
+42
View File
@@ -0,0 +1,42 @@
import { WebhookTriggerEvents } from "@prisma/client";
import prisma from "@calcom/prisma";
export type GetSubscriberOptions = {
userId: number;
eventTypeId: number;
triggerEvent: WebhookTriggerEvents;
};
const getWebhooks = async (options: GetSubscriberOptions) => {
const { userId, eventTypeId } = options;
const allWebhooks = await prisma.webhook.findMany({
where: {
OR: [
{
userId,
},
{
eventTypeId,
},
],
AND: {
eventTriggers: {
has: options.triggerEvent,
},
active: {
equals: true,
},
},
},
select: {
subscriberUrl: true,
payloadTemplate: true,
appId: true,
},
});
return allWebhooks;
};
export default getWebhooks;
-3
View File
@@ -3,7 +3,6 @@ import { z } from "zod";
import { _BookingModel as Booking } from "@calcom/prisma/zod";
const schemaBookingBaseBodyParams = Booking.pick({
uid: true,
userId: true,
eventTypeId: true,
title: true,
@@ -13,7 +12,6 @@ const schemaBookingBaseBodyParams = Booking.pick({
const schemaBookingCreateParams = z
.object({
uid: z.string(),
eventTypeId: z.number(),
title: z.string(),
startTime: z.date().or(z.string()),
@@ -25,7 +23,6 @@ export const schemaBookingCreateBodyParams = schemaBookingBaseBodyParams.merge(s
const schemaBookingEditParams = z
.object({
uid: z.string().optional(),
title: z.string().optional(),
startTime: z.date().optional(),
endTime: z.date().optional(),
+15
View File
@@ -0,0 +1,15 @@
import { withValidation } from "next-validations";
import { z } from "zod";
import { baseApiParams } from "./baseApiParams";
// Extracted out as utility function so can be reused
// at different endpoints that require this validation.
export const schemaQueryUserId = baseApiParams
.extend({
userId: z
.string()
.regex(/^\d+$/)
.transform((id) => parseInt(id)),
})
.strict();
+12 -7
View File
@@ -59,7 +59,6 @@ export const schemaUserBaseBodyParams = User.pick({
timeZone: true,
weekStart: true,
endTime: true,
metadata: true,
bufferTime: true,
theme: true,
defaultScheduleId: true,
@@ -93,7 +92,6 @@ const schemaUserEditParams = z.object({
.optional()
.nullable(),
locale: z.nativeEnum(locales).optional().nullable(),
metadata: jsonSchema,
});
// @note: These are the values that are editable via PATCH method on the user Model,
@@ -116,14 +114,20 @@ const schemaUserCreateParams = z.object({
.optional()
.nullable(),
locale: z.nativeEnum(locales).optional(),
metadata: jsonSchema,
createdDate: z.string().or(z.date()).optional(),
});
// @note: These are the values that are editable via PATCH method on the user Model,
// merging both BaseBodyParams with RequiredParams, and omiting whatever we want at the end.
export const schemaUserEditBodyParams = schemaUserBaseBodyParams.merge(schemaUserEditParams).omit({});
export const schemaUserCreateBodyParams = schemaUserBaseBodyParams.merge(schemaUserCreateParams).omit({});
export const schemaUserEditBodyParams = schemaUserBaseBodyParams
.merge(schemaUserEditParams)
.omit({})
.strict();
export const schemaUserCreateBodyParams = schemaUserBaseBodyParams
.merge(schemaUserCreateParams)
.omit({})
.strict();
// @note: These are the values that are always returned when reading a user
export const schemaUserReadPublic = User.pick({
@@ -134,7 +138,6 @@ export const schemaUserReadPublic = User.pick({
emailVerified: true,
bio: true,
avatar: true,
metadata: true,
timeZone: true,
weekStart: true,
endTime: true,
@@ -150,4 +153,6 @@ export const schemaUserReadPublic = User.pick({
createdDate: true,
verified: true,
invitedTo: true,
}).merge(schemaUserEditBodyParams);
});
export const schemaUsersReadPublic = z.array(schemaUserReadPublic);