This commit is contained in:
Agusti Fernandez Pardo committed 2022-03-30 14:17:55 +02:00
1 parent 39ae2aed37
commit 1de7bc4146
126 files changed
+1240 -992

No files matched your search

+6 -6
View File
@@ -1,9 +1,9 @@
import { NextMiddleware } from "next-api-middleware";
import { nanoid } from "nanoid";
import { NextMiddleware } from "next-api-middleware";
export const addRequestId: NextMiddleware = async (_req, res, next) => {
// Apply header
res.setHeader("X-Response-ID", nanoid());
// Let remaining middleware and API route execute
await next();
};
// Apply header
res.setHeader("Calcom-Response-ID", nanoid());
// Let remaining middleware and API route execute
await next();
};
+2 -4
View File
@@ -1,5 +1,5 @@
import { NextMiddleware } from "next-api-middleware";
import * as Sentry from "@sentry/nextjs";
import { NextMiddleware } from "next-api-middleware";
export const captureErrors: NextMiddleware = async (_req, res, next) => {
try {
@@ -7,10 +7,8 @@ export const captureErrors: NextMiddleware = async (_req, res, next) => {
// middleware and the API route handler
await next();
} catch (err) {
const eventId = Sentry.captureException(err);
console.log(eventId)
Sentry.captureException(err);
res.status(500);
res.json({ error: err });
}
};
+6 -8
View File
@@ -1,19 +1,17 @@
import { NextMiddleware } from "next-api-middleware";
export const httpMethod = (
allowedHttpMethod: "GET" | "POST" | "PATCH" | "DELETE"
): NextMiddleware => {
export const httpMethod = (allowedHttpMethod: "GET" | "POST" | "PATCH" | "DELETE"): NextMiddleware => {
return async function (req, res, next) {
if (req.method === allowedHttpMethod || req.method == "OPTIONS") {
await next();
} else {
res.status(404);
res.status(405).json({ message: `Only ${allowedHttpMethod} Method allowed` });
res.end();
}
};
};
export const postOnly = httpMethod("POST");
export const getOnly = httpMethod("GET");
export const patchOnly = httpMethod("PATCH");
export const deleteOnly = httpMethod("DELETE");
export const HTTP_POST = httpMethod("POST");
export const HTTP_GET = httpMethod("GET");
export const HTTP_PATCH = httpMethod("PATCH");
export const HTTP_DELETE = httpMethod("DELETE");
+14 -11
View File
@@ -1,20 +1,23 @@
import { NextMiddleware } from "next-api-middleware";
// import { nanoid } from "nanoid";
import prisma from "@calcom/prisma";
const dateInPast = function (firstDate: Date, secondDate: Date) {
if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) {
return true;
}
}
if (firstDate.setHours(0, 0, 0, 0) <= secondDate.setHours(0, 0, 0, 0)) {
return true;
}
};
const today = new Date();
export const verifyApiKey: NextMiddleware = async (req, res, next) => {
const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.apiKey as string } });
if (!apiKey) {
res.status(400).json({ error: 'Your api key is not valid' });
throw new Error('No api key found');
}
if (apiKey.expiresAt && dateInPast(apiKey.expiresAt, today)) await next();
else res.status(400).json({ error: 'Your api key is not valid' });
const apiKey = await prisma.apiKey.findUnique({ where: { id: req.query.apiKey as string } });
if (!apiKey) {
res.status(400).json({ error: "Your api key is not valid" });
throw new Error("No api key found");
}
if (apiKey.expiresAt && apiKey.userId && dateInPast(apiKey.expiresAt, today)) {
res.setHeader("Calcom-User-ID", apiKey.userId);
await next();
} else res.status(400).json({ error: "Your api key is not valid" });
};
+11 -8
View File
@@ -1,19 +1,22 @@
import { label } from "next-api-middleware";
import { addRequestId } from "./addRequestid";
import { captureErrors } from "./captureErrors";
import { HTTP_POST, HTTP_DELETE, HTTP_PATCH, HTTP_GET, httpMethod } from "./httpMethods";
import { verifyApiKey } from "./verifyApiKey";
import { postOnly, deleteOnly, patchOnly, getOnly } from "./httpMethods";
const withMiddleware = label(
{
getOnly,
patchOnly,
postOnly,
deleteOnly,
HTTP_GET,
HTTP_PATCH,
HTTP_POST,
HTTP_DELETE,
addRequestId,
verifyApiKey,
sentry: captureErrors, // <-- Optionally alias middleware
sentry: captureErrors,
httpMethod: httpMethod("GET" || "DELETE" || "PATCH" || "POST"),
},
["sentry","verifyApiKey"] // <-- Provide a list of middleware to call automatically
["sentry", "verifyApiKey", "httpMethod", "addRequestId"] // <-- Provide a list of middleware to call automatically
);
export { withMiddleware };
export { withMiddleware };
+22
View File
@@ -0,0 +1,22 @@
import { User, ApiKey } from "@calcom/prisma/client";
// Base response, used for all responses
export type BaseResponse = {
message?: string;
error?: Error;
};
// User
export type UserResponse = BaseResponse & {
data?: Partial<User>;
};
export type UsersResponse = BaseResponse & {
data?: Partial<User>[];
};
// API Key
export type ApiKeyResponse = BaseResponse & {
data?: Partial<ApiKey>;
};
export type ApiKeysResponse = BaseResponse & {
data?: Partial<ApiKey>[];
};
+4 -4
View File
@@ -1,4 +1,4 @@
export const stringifyISODate = (date: Date|undefined): string => {
return `${date?.toISOString()}`
}
// TODO: create a function that takes an object and returns a stringified version of dates of it.
export const stringifyISODate = (date: Date | undefined): string => {
return `${date?.toISOString()}`;
};
// TODO: create a function that takes an object and returns a stringified version of dates of it.
+11 -14
View File
@@ -1,19 +1,16 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schemaApiKey = z
.object({
// We need to cast the date as strings as when we get it from the json response
// we serve in api it is a string too (JSON doesn't directly support Date types)
createdAt: z.date().optional().or(z.string().optional()),
expiresAt: z.date().optional(), // default is 30 days
note: z.string().min(1).optional(),
})
.strict(); // Adding strict so that we can disallow passing in extra fields
const withValidApiKey = withValidation({
schema: schemaApiKey,
import { _ApiKeyModel as ApiKey } from "@calcom/prisma/zod";
export const schemaApiKeyBodyParams = ApiKey.omit({ id: true, userId: true, createdAt: true });
export const schemaApiKeyPublic = ApiKey.omit({
id: true,
userId: true,
});
export const withValidApiKey = withValidation({
schema: schemaApiKeyBodyParams,
type: "Zod",
mode: "body",
});
export { schemaApiKey, withValidApiKey };
+2 -2
View File
@@ -7,13 +7,13 @@ const schemaAvailability = z
userId: z.number(),
eventTypeId: z.number(),
scheduleId: z.number(),
days: z.array(z.number()),
date: z.date().or(z.string()),
startTime: z.string(),
endTime: z.string(),
})
.strict();
.strict();
const withValidAvailability = withValidation({
schema: schemaAvailability,
type: "Zod",
+1 -3
View File
@@ -1,9 +1,7 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schemaBookingReference = z
.object({})
.strict();
const schemaBookingReference = z.object({}).strict();
const withValidBookingReference = withValidation({
schema: schemaBookingReference,
type: "Zod",
+1 -1
View File
@@ -15,7 +15,7 @@ const schemaBooking = z
rejected: z.boolean().default(false),
paid: z.boolean().default(false),
})
.strict();
.strict();
const withValidBooking = withValidation({
schema: schemaBooking,
type: "Zod",
+1 -3
View File
@@ -1,9 +1,7 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schemaCredential = z
.object({})
.strict();
const schemaCredential = z.object({}).strict();
const withValidCredential = withValidation({
schema: schemaCredential,
type: "Zod",
+1 -3
View File
@@ -1,9 +1,7 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schemaDailyEventReference = z
.object({})
.strict();
const schemaDailyEventReference = z.object({}).strict();
const withValidDailyEventReference = withValidation({
schema: schemaDailyEventReference,
type: "Zod",
+1 -3
View File
@@ -1,9 +1,7 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schemaDestinationCalendar = z
.object({})
.strict();
const schemaDestinationCalendar = z.object({}).strict();
const withValidDestinationCalendar = withValidation({
schema: schemaDestinationCalendar,
type: "Zod",
+1 -1
View File
@@ -8,7 +8,7 @@ const schemaEventType = z
length: z.number().min(1).max(1440), // max is a full day.
description: z.string().min(3).optional(),
})
.strict();
.strict();
const withValidEventType = withValidation({
schema: schemaEventType,
type: "Zod",
+1 -3
View File
@@ -1,9 +1,7 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schemaMembership = z
.object({})
.strict();
const schemaMembership = z.object({}).strict();
const withValidMembership = withValidation({
schema: schemaMembership,
type: "Zod",
+1 -3
View File
@@ -1,9 +1,7 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schemaPayment = z
.object({})
.strict();
const schemaPayment = z.object({}).strict();
const withValidPayment = withValidation({
schema: schemaPayment,
type: "Zod",
+1 -3
View File
@@ -1,9 +1,7 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schemaSchedule = z
.object({})
.strict();
const schemaSchedule = z.object({}).strict();
const withValidSchedule = withValidation({
schema: schemaSchedule,
type: "Zod",
+1 -3
View File
@@ -1,9 +1,7 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schemaSelectedCalendar = z
.object({})
.strict();
const schemaSelectedCalendar = z.object({}).strict();
const withValidSelectedCalendar = withValidation({
schema: schemaSelectedCalendar,
type: "Zod",
+13
View File
@@ -0,0 +1,13 @@
import { z } from "zod";
// Extracted out as utility function so can be reused
// at different endpoints that require this validation.
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(),
// version required for supporting /v1/ redirect to query in api as *?version=1
version: z.string().optional(),
})
.strict();
+6 -11
View File
@@ -1,23 +1,18 @@
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.
const schemaQueryIdAsString = 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(),
// since nextjs parses query params as strings,
// we need to cast them to numbers using z.transform() and parseInt()
id: z.string()
export const schemaQueryIdAsString = baseApiParams
.extend({
id: z.string(),
})
.strict();
const withValidQueryIdString = withValidation({
export const withValidQueryIdString = withValidation({
schema: schemaQueryIdAsString,
type: "Zod",
mode: "query",
});
export { schemaQueryIdAsString, withValidQueryIdString };
@@ -1,15 +1,12 @@
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.
const schemaQueryIdParseInt = 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(),
// since nextjs parses query params as strings,
// we need to cast them to numbers using z.transform() and parseInt()
export const schemaQueryIdParseInt = baseApiParams
.extend({
id: z
.string()
.regex(/^\d+$/)
@@ -17,10 +14,8 @@ const schemaQueryIdParseInt = z
})
.strict();
const withValidQueryIdTransformParseInt = withValidation({
export const withValidQueryIdTransformParseInt = withValidation({
schema: schemaQueryIdParseInt,
type: "Zod",
mode: "query",
});
export { schemaQueryIdParseInt, withValidQueryIdTransformParseInt };
+1 -1
View File
@@ -9,7 +9,7 @@ const schemaTeam = z
bio: z.string().min(3).optional(),
logo: z.string().optional(),
})
.strict();
.strict();
const withValidTeam = withValidation({
schema: schemaTeam,
type: "Zod",
+23 -57
View File
@@ -1,63 +1,29 @@
import { withValidation } from "next-validations";
import { z } from "zod";
import { schemaEventType } from "./eventType";
import { schemaApiKey } from "./apiKey";
import { schemaDestinationCalendar } from "./destination-calendar";
import { schemaWebhook } from "./webhook";
import { schemaAvailability } from "./availability";
import { schemaSelectedCalendar } from "./selected-calendar";
import { schemaBooking } from "./booking";
import { schemaMembership } from "./membership";
import { schemaSchedule } from "./schedule";
import { schemaCredential } from "./credential";
import { _UserModel as User } from "@calcom/prisma/zod";
const schemaUser = z
.object({
username: z.string().min(3),
name: z.string().min(3),
email: z.string().email(), // max is a full day.
emailVerified: z.date().optional(),
password: z.string().optional(),
bio: z.string().min(3).optional(),
avatar: z.string().optional(),
timeZone: z.string().default("Europe/London"),
weekStart: z.string().default("Sunday"),
bufferTime: z.number().default(0),
hideBranding: z.boolean().default(false),
theme: z.string().optional(),
trialEndsAt: z.date().optional(),
eventTypes: z.array((schemaEventType)).optional(),
credentials: z.array((schemaCredential)).optional(),
teams: z.array((schemaMembership)).optional(),
bookings: z.array((schemaBooking)).optional(),
schedules: z.array((schemaSchedule)).optional(),
defaultScheduleId: z.number().optional(),
selectedCalendars: z.array((schemaSelectedCalendar)).optional(),
completedOnboarding: z.boolean().default(false),
locale: z.string().optional(),
timeFormat: z.number().optional().default(12),
twoFactorEnabled: z.boolean().default(false),
twoFactorSecret: z.string().optional(),
identityProvider: z.enum(["CAL", "SAML", "GOOGLE"]).optional().default("CAL"),
identityProviderId: z.string().optional(),
availability: z.array((schemaAvailability)).optional(),
invitedTo: z.number().optional(),
plan: z.enum(['FREE', 'TRIAL', 'PRO']).default("TRIAL"),
webhooks: z.array((schemaWebhook)).optional(),
brandColor: z.string().default("#292929"),
darkBrandColor: z.string().default("#fafafa"),
destinationCalendar: z.array(schemaDestinationCalendar).optional(), // FIXME: instanceof doesnt work here
away: z.boolean().default(false),
metadata: z.object({}).optional(),
verified: z.boolean().default(false),
apiKeys: z.array((schemaApiKey)).optional(),
})
.strict();
const withValidUser = withValidation({
schema: schemaUser,
export const schemaUserBodyParams = User.omit({
id: true,
createdAt: true,
password: true,
twoFactorEnabled: true,
twoFactorSecret: true,
});
export const schemaUserPublic = User.omit({
identityProvider: true,
identityProviderId: true,
plan: true,
metadata: true,
password: true,
twoFactorEnabled: true,
twoFactorSecret: true,
trialEndsAt: true,
completedOnboarding: true,
});
export const withValidUser = withValidation({
schema: schemaUserBodyParams,
type: "Zod",
mode: "body",
});
export { schemaUser, withValidUser };
+1 -3
View File
@@ -1,9 +1,7 @@
import { withValidation } from "next-validations";
import { z } from "zod";
const schemaWebhook = z
.object({})
.strict();
const schemaWebhook = z.object({}).strict();
const withValidWebhook = withValidation({
schema: schemaWebhook,